在Spring'中自动连接bean;s的Java配置
是否可以在用Java编写的Spring配置中使用Spring的在Spring'中自动连接bean;s的Java配置,java,spring,Java,Spring,是否可以在用Java编写的Spring配置中使用Spring的@Autowired注释 例如: @Configuration public class SpringConfiguration{ @Autowired DataSource datasource; @Bean public DataSource dataSource(){ return new dataSource(); } // ... } 显然,数据源接口不能直接实例
@Autowired
注释
例如:
@Configuration
public class SpringConfiguration{
@Autowired
DataSource datasource;
@Bean
public DataSource dataSource(){
return new dataSource();
}
// ...
}
显然,数据源接口不能直接实例化,但为了简化,我在这里直接实例化了它。目前,当我尝试上述操作时,datasource对象仍然为null,并且不是由Spring自动连接的
通过返回一个FactoryBean
,我使@Autowired
成功地使用HibernateSessionFactory
对象
所以我的问题是:对于数据源
,有没有办法做到这一点?或者更一般地说,在SpringJava配置中自动连接bean的方法是什么
我应该注意,我使用的是Spring 3.2版。如果需要在同一
@Configuration
文件中引用数据源
bean,只需调用bean方法即可
@Bean
public OtherBean someOtherBean() {
return new OtherBean(dataSource());
}
或者将其自动连接到@Bean
方法中
@Bean
public OtherBean someOtherBean(DataSource dataSource) {
return new OtherBean(dataSource);
}
@Configuration
类的生命周期有时会阻止像您建议的那样进行自动连接。也许您可以使用构造函数将其他配置文件中的一些bean注入到您的配置中,而@Autowired在配置文件中可能无法正常工作
@Configuration
public class AppConfig {
private DataSource dataSource;
public AppConfig(DataSource dataSource) {
this.dataSource = dataSource;
}
@Bean
public OtherBean otherBean(){
return new OtherBean(dataSource);
}
}
无法自动连接使用@Configuration类配置的bean
因此,为了完整性,您不能同时使用@Autowired和@configuration:是的,在spring@configuration类中使用@Autowired注释在技术上是可能的,并且它的工作方式与其他spring bean相同。但是公认的答案表明了原始问题应该如何解决。为什么需要在那里自动连接它?我只是试图将xml配置文件转换为Java配置文件。我想既然我可以在xml中通过id引用bean,为什么我不应该在Java配置文件中对其使用autowire注释呢?这很有趣,正如您所描述的那样,它可以正常工作。为什么呢?你能给我指出任何关于这个问题的Spring文档吗?顺便说一下,非常感谢您的回答。@Avanst请参阅文档。@SotiriosDelimanolis,今天我花了几个小时来寻找将成员注入配置类所导致的类似问题。@heez
DataSource
是一个接口(java.sql.DataSource
)。我不理解您的担忧。更新了@SotiriosDelimanolis评论中引用的文档链接: