因此,我的配置类之一包括(测试/生产)DatabaseConfig 类,并且 Activity 配置文件会选择正确的一个。但是当DatabaseConfig类运行时,它的dataSource ivar为null。
我做了一个调试,我的TestingDatabaseConfig的dataSource()方法在DatabaseConfig的localContainerEntityManagerFactoryBean()运行之前运行。
我想我的问题是,为什么这不起作用,它应该起作用吗?我做错了什么?
@Configuration
@Profile({"testing-db", "production-db"})
@Import({TestingDatabaseConfig.class, ProductionDatabaseConfig.class})
@EnableTransactionManagement
public class DatabaseConfig
{
@Resource
private DataSource dataSource;
@Bean(name = "entityManager")
public LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean()
{
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(this.dataSource);
// other config
return entityManagerFactoryBean;
}
// ... other db related beans stuff ...
}
@Configuration
@Profile("testing-db")
public class TestingDatabaseConfig implements DatabaseConfigInterface
{
@Bean(name="dataSource")
public DataSource dataSource()
{
JDBCDataSource dataSource = new JDBCDataSource();
dataSource.setDatabase("jdbc:hsqldb:mem:testing");
dataSource.setUser("sa");
return dataSource;
}
}
最佳答案
当然,它们不会在调用构造函数之前注入(inject)。
使用@PostConstruct 。这是一个很好的例子:http://www.mkyong.com/spring/spring-postconstruct-and-predestroy-example/
关于java - spring 配置在创建 bean 之前没有 Autowiring ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11303476/