如果我指定应该注入属性的内容,例如
<property name="xxx" ref="some_bean" />
或
<property name="xxx">
<bean .../>
</property>
然后我必须写一个setter方法。
我可以使用一些注释来避免这种情况,例如@autowired
吗?
答案 0 :(得分:1)
您可以使用构造函数注入执行此操作。 3种主要方法:
XML:
<bean id="beanA" class="com.BeanA">
<constructor-arg ref="beanB"/>
</bean>
<bean id="beanB" class="com.BeanB"/>
JavaConfig:
@Configuration
public class MyConfig {
@Bean
public BeanA beanA() {
return new BeanA(beanB());
}
@Bean
public BeanB beanB() {
return new BeanB();
}
}
自动装配:
@Component
public class BeanA {
private final BeanB beanb;
// This assumes that there is a BeanB in your application context already
@Autowired
public BeanA(final BeanB beanB) {
this.beanB = beanB;
}
}
您可以进一步采用自动装配,并直接连接到现场:
@Component
public class BeanA {
// This assumes that there is a BeanB in your application context already
@Autowired
private final BeanB beanb;
}