到目前为止,我已经设法避免为我的 Spring Boot Maven 项目(除了 pom)开发任何 xml 文件,它们都是在编译时生成的,我希望通过在此处指定的运行命令中定义我的配置文件来保持这种方式.
通过简单地使用@ComponentScan我的主类来启用组件扫描并将我的DAO 标记为@Repository ,我已经成功地自动装配了我的UserDAOmySQLImpl 类(它继承了UserDAO)。
@Autowired
private UserDAO userDAO;
然后期待在我们使用 db8 实现的 Live 中添加第二个 DAO,我需要应用程序确定需要使用哪个 UserDAO 实现。配置文件似乎是答案。
经过一番阅读,似乎我主要需要添加某种配置类和外部 xml 来管理这些配置文件和组件,尽管这看起来很乱,我希望没有必要。
我已经被两个实现标记为:
@Repository
@Profile("dev")
public class UserDAOmySQLImpl implements UserDAO {...
-
@Repository
@Profile("dev")
public class UserDAOdb8Impl implements UserDAO {...
然后通过此处指定的 Maven 目标设置活动配置文件,希望这将是一个很好的干净解决方案,因此我可以分别在目标中为我们的开发和实时构建脚本指定活动配置文件。
我目前的测试目标是:
spring-boot:run -Drun.profiles=dev
但是,在构建时,我收到一个错误,即两个 bean 都被拾取。
*No qualifying bean of type [com.***.studyplanner.integration.UserDAO] is defined: expected single matching bean but found 2: userDAOdb8Impl,userDAOmySQLImpl*
问题
Maven 目标中设置的配置文件是使用@Profile 标记时要检查的配置文件吗?
当配置文件没有正确设置时,为什么 Spring 会同时选择两个实现?
关于实现我正在寻找的东西的干净方式的任何建议?
奖金
我真的很想在应用程序中设置配置文件,因为很容易检查环境文件是否存在来决定使用哪个配置文件,尽管我正在努力复制它(在Spring Profiles 示例中找到
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
//Enable a "live" profile
context.getEnvironment().setActiveProfiles("live");
context.register(AppConfig.class);
context.refresh();
((ConfigurableApplicationContext) context).close();
}
进入我正在处理的应用程序中不寻常的主类,我犹豫要不要玩。
public class StudyPlannerApplication {
...
public static void main(String[] args) {
SpringApplication.run(StudyPlannerApplication.class, args);
}
...
}
任何帮助将不胜感激。
干杯,斯科特。