我正在学习 Spring(并关注 Spring in Action),因为我正在尝试理解一些概念;然后我观察到以下行为。
场景:
我想通过使用“byType” Autowiring 选项来 Autowiring 类中的列表属性。所以我创建了 util:list bean;成功注入(inject)...所以这里并不奇怪:)。
然后我在同一个类中添加了一个新的列表属性(不同的类层次结构:当然);然后也可以在不做任何额外接线的情况下注入(inject)......:O
任何人都可以解释一下幕后发生的事情吗?
下面是一些代码片段。
public interface Performer {
public void perform();
}
public interface Instrument {
public void play();
}
public class Show implements Audotorium {
Logger logger = Logger.getLogger(Show.class.getName());
List<Performer> performerList;
List<Instrument> instruments;
public void setPerformerList(List<Performer> performerList) {
this.performerList = performerList;
}
public void setInstruments(List<Instrument> instruments) {
this.instruments = instruments;
}
public void show() {
Iterator<Performer> performerItr = performerList.iterator();
while (performerItr.hasNext()) {
performerItr.next().perform();
}
Iterator<Instrument> instrumentItr = instruments.iterator();
while (instrumentItr.hasNext()) {
instrumentItr.next().play();
}
}
}
主类
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("/META-INF/spring-context.xml");
((Show) context.getBean("show")).show();
}
Bean 配置:
<bean id="juggler" class="com.learning.Juggler"/>
<bean id="magcian" class="com.learning.Magician"/>
<bean id="kenny" class="com.learning.Instrumentalist">
<property name="song" value="bay finger bay finger"/>
<property name="instrument" ref="saxphone"/>
</bean>
<bean id="hunk" class="com.learning.OneManBand" autowire="byType">
<property name="song" value="bay finger bay finger"/>
<property name="instruments">
<list>
<ref bean="saxphone"/>
<ref bean="guitar"/>
<ref bean="harmonica"/>
</list>
</property>
</bean>
<bean id="totalBeanBags" class="java.lang.Integer" factory-method="valueOf">
<constructor-arg value="#{performerList.size()}"/>
</bean>
<bean id="saxphone" class="com.learning.SaxPhone"/>
<bean id="guitar" class="com.learning.GenaricInstument">
<property name="instrumentSound" value="guitar sound"/>
</bean>
<bean id="harmonica" class="com.learning.GenaricInstument">
<property name="instrumentSound" value="harmonica sound"/>
</bean>
<util:list id="performerList"/>
<bean id="show" class="com.learning.Show" autowire="byType">
</bean>
输出:
JUGGLING 10 BEANBAGS
Showing some crazy magicSSsssSSSsss.....
Playing bay finger bay finger : TOO TOO TOO
Playing bay finger bay finger : TOO TOO TOO
guitar sound
harmonica sound
----Now its music time----
TOO TOO TOO
guitar sound
harmonica sound
最佳答案
与
<util:list id="performerList"/>
您创建了一个空列表,它未被使用,您可以将其删除。
您有一个 Performer
类型的 bean “OneManBand”。
当 spring 尝试 Autowiring 时 setPerformerList
,它会自动创建一个 List<Performer>
类型的列表并将其用作参数。 Spring 放置 Performer
类型的所有 bean进入该列表。
Instrument
的列表以相同的方式创建和注入(inject)。
这是 spring 的一个非常方便的功能,我经常使用它来构建注册表,收集特定类型的所有 bean 并对其进行操作。
关于java - Spring Autowiring byType 与 util :list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36949526/