Spring java配置bean定义覆盖

时间:2016-07-25 10:37:41

标签: spring-java-config

在我的Spring应用程序中,我有一个名为@Configuration的主要课程,让我们说ConfigApplication。我还有一些基于配置文件的配置类ConfigDevConfigProd。情况恢复如下:

@Configuration
@ComponentScan("fr.gf.predication.*")
@Import(value = ConfigSecurity.class)
@PropertySource("classpath:configuration/default.properties")
public class ConfigApplication {

    @Bean
    public JpaTransactionManager transactionManager() {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
        return transactionManager;
    }

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
        dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
        dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
        dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
        return dataSource;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();

        entityManagerFactoryBean.setJpaVendorAdapter(vendorAdapter);
        entityManagerFactoryBean.setPackagesToScan(MODEL_PACKAGE);
        entityManagerFactoryBean.setDataSource(dataSource());
        entityManagerFactoryBean.setJpaProperties(loadHibernateConfiguration());

        return entityManagerFactoryBean;
    }
}

如果我选择将dataSource bean定义移动到我的环境之间具有特定配置(例如,有和没有连接池),我将不得不复制所有其他bean定义(entityManagerFactorytransactionManager)因为他们需要dataSource bean。

我试图在我的ConfigProd类中覆盖这个bean定义,但它似乎被Spring忽略,直到它已经在主配置类中加载了bean ...
有没有办法实现这种特定于环境的配置?或者我应该重新考虑这些类的设计吗?

1 个答案:

答案 0 :(得分:0)

最后,我找到了解决方案。我刚在@Import(ConfigApplication.class)课程中添加了注释ConfigProd。这样,dataSource bean定义将按预期覆盖。