gpt4 book ai didi

java - 如何在启动时 Autowiring 配置文件配置类?

转载 作者:太空宇宙 更新时间:2023-11-04 06:49:19 25 4
gpt4 key购买 nike

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

我在 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);
}
}

配置属性:

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 注释,一切都会正确连接。

最佳答案

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

关于java - 如何在启动时 Autowiring 配置文件配置类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23561065/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com