是否可以在用Java编写的Spring配置中使用Spring的@Autowired
注释?
例如:
@Configuration
public class SpringConfiguration{
@Autowired
DataSource datasource;
@Bean
public DataSource dataSource(){
return new dataSource();
}
// ...
}
显然,DataSource接口不能直接实例化,但我在这里直接实例化它是为了简化。目前,当我尝试上述操作时,数据源对象仍然为空,并且不会由Spring自动装配。
我通过返回@Autowired
让SessionFactory
成功使用Hibernate FactoryBean<SessionFactory>
对象。
所以我的问题具体说明:对于DataSource
,有没有办法做到这一点?或者更一般地说,在Spring Java配置中自动装配bean的方法是什么?
我应该注意到我使用的是Spring 3.2版。
答案 0 :(得分:29)
如果需要在同一DataSource
文件中引用@Configuration
bean,只需调用bean方法。
@Bean
public OtherBean someOtherBean() {
return new OtherBean(dataSource());
}
或将其自动装入@Bean
方法
@Bean
public OtherBean someOtherBean(DataSource dataSource) {
return new OtherBean(dataSource);
}
@Configuration
课程的生命周期有时会像您建议的那样阻止自动装配。
答案 1 :(得分:0)
出于完整性考虑:是的,在技术上可以在spring @Configuration类中使用@Autowired注释,并且其工作方式与其他spring bean相同。但是,被接受的答案表明了应如何解决原始问题。
答案 2 :(得分:-1)
也许您可以使用构造函数将其他配置文件中的bean注入您的配置,而@Autowired可能无法在配置文件中正常工作
@Configuration
public class AppConfig {
private DataSource dataSource;
public AppConfig(DataSource dataSource) {
this.dataSource = dataSource;
}
@Bean
public OtherBean otherBean(){
return new OtherBean(dataSource);
}
}
答案 3 :(得分:-2)
使用@Configuration类配置的bean无法自动装配,
因此您不能同时使用@Autowiring和@configuration