Spring3Setter注入:当您需要在另一个类的构造函数中使用注入的类时,如何完成?
如果我有:Spring3Setter注入:当您需要在另一个类的构造函数中使用注入的类时,如何完成?,spring,dependency-injection,Spring,Dependency Injection,如果我有: @Component class Foo { @Autowired private Bar b; //where b is @Service public Foo(){ //if i need to use b here, what do i need to do? b.something(); // <-- b is null so it'll crash here }
@Component
class Foo {
@Autowired
private Bar b; //where b is @Service
public Foo(){
//if i need to use b here, what do i need to do?
b.something(); // <-- b is null so it'll crash here
}
public void setB(Bar b){
this.b = b;
}
}
您需要在application-context.xml或等效的spring配置文件中定义bean,如下所示:
<bean id="b" class="Bar" />
<bean id="f" class="Foo">
<constructor-arg ref="b" />
</bean>
只需从Foo类中删除这些@Component和@Autowired注释@组件将在组件扫描期间尝试查找默认构造函数,但bean创建过程失败。代码正常,是的,@Autowired可用于连接构造函数参数
您还可以进行setter注入,然后声明init方法或使用@PostConstruct初始化bean。您可以创建一个用@PostConstruct注释的方法,如前所述: 这需要额外的依赖项和一些配置 通常的方法是让bean实现Spring接口初始化bean。 您可以实现的AfterPropertieSet方法将在注入其所有依赖项后由Spring触发 您最好使用注释,一旦配置了注释,它就更简单、更易于阅读,并且与JavaEE兼容
<bean id="b" class="Bar" />
<bean id="f" class="Foo">
<constructor-arg ref="b" />
</bean>