java - spring 配置在创建 bean 之前没有 Autowiring ?

标签 java spring

因此,我的配置类之一包括(测试/生产)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/

相关文章:

java - Kinesis 工作人员错误 : Caught exception when initializing LeaseCoordinator

java - HttpURLConnection - 在 servlet 中获取普通网站而不是移动网站

Java 8 时区 ZoneRulesException : Unknown time-zone ID: EST

java - 如何修复java中的UnknownHostException

java - 在 Spring Batch 上下文中将子字符串与 SpEL 一起使用

java - Mysql 连接 Spring Boot 困难

java - 检查所有 Dto 成员中的 null 条件。如果不是,则将值设置为 pojo 类的相同属性

java - 使用 spring-boot 对相同 URL 进行不同的身份验证方式

java - Spring BeanCurrentlyInCreationException

java - 向服务发送表单