如何在启动时自动配置配置文件配置类?

时间:2014-05-09 09:26:46

标签: java spring datasource autowired

我想创建不同的数据库配置文件类,每个类都用于开发,生产和测试。

我在http://spring.io/blog/2011/02/14/spring-3-1-m1-introducing-profile/的帮助下尝试了以下操作,但它没有正确接线。为什么呢?

 interface DataConfig {
        DataSource dataSource();
    }

    @Configuration
    @Profile("dev")
    public class StandaloneDataConfig implements DataConfig {
        @Bean
        @Override
        public dataSource dataSource() {
            //return the ds
        }
    }

    @Configuration
    @Profile("prod")
    public class JndiDataConfig implements DataConfig { ... }

    @Configuration
    @PropertySource({"classpath:config.properties"})
    class AppConfig {
        @Autowired
        private DataConfig cfg;

    }

@Configuration
@ComponentScan
@Import(AppConfig.class)
@EnableTransactionManagement
public class SpringBootConfig extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }
}

config.properties:

spring.profiles.active=dev

结果:启动时出现异常

Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private DataConfig dataConfig; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [DataConfig] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
    ... 34 common frames omitted

Spring 4.0.3.RELEASE

我的设置似乎总体上起作用:如果我删除其中一个数据库上的@Profile注释,一切都正确连接。

2 个答案:

答案 0 :(得分:1)

您需要将config.properties文件重命名为application.properties,以便Spring Boot自动选择它。

答案 1 :(得分:0)

我还没有对您的配置进行测试,但我最好的猜测(我已经为this post做了一些调查)是@PropertySources无法用于@Conditional自动装配发生时带注释的@Configuration类。

根据source code@Profile是一种@Conditional注释风格,带有Condition实现。 要求@PropertySource在需要时可用,我认为您需要自己的自定义@Conditional实施,就像我在上面提到的SO帖子中那样,您定义的不是Condition而是ConfigurationCondition {1}}确保在ConfigurationPhase.REGISTER_BEAN阶段使用。