我已经成功地避免迄今我的春节,引导Maven项目(除了POM)与他们所有的开发任何XML文件的编译生成,我希望通过运行命令中定义我的配置,如为保持这种方式在这里。
通过简单地使用@ ComponentScan我的主类来启用组件的扫描并将DAO标记为@ Repository,我成功地设法自动装配了UserDAOmySQLImpl类(继承了UserDAO)。
@Autowired
private UserDAO userDAO;
然后期待在Live中使用db8实现时添加第二个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
但是,在构建时,我收到两个豆都被拾取的错误。
*No qualifying bean of type [com.***.studyplanner.integration.UserDAO] is defined: expected single matching bean but found 2: userDAOdb8Impl,userDAOmySQLImpl*
问题
使用@Profile标记时,是否要对照Maven目标中设置的配置文件?
如果未正确设置概要文件,则为什么不选择两个实现,为什么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);
}
...
}
任何帮助将不胜感激。
干杯,斯科特。
愚蠢的我,证明阅读了我发现的问题的证据是,糟糕的复制和粘贴工作意味着两个DAO实现都将@profile设置为“ Dev”。将db8 DAO更改为@Profile(“ live”)之后,以上方法可以正常工作。
因此,在使用Maven和Spring Boot时,基于配置文件选择存储库实际上非常容易。
1)确保您的主类具有@ComponentScan批注
@ComponentScan
public class StudyPlannerApplication {
2)根据您要为其选择的配置文件,使用@Profile标记为组件添加标签
@Repository
@Profile("dev")
public class UserDAOdb8Impl implements UserDAO {...
--
@Repository
@Profile("live")
public class UserDAOdb8Impl implements UserDAO {...
3)将您的个人资料发送给您的Maven目标
spring-boot:run -Drun.profiles=dev
希望这会对其他人有所帮助,因为我还没有像在网络上其他地方那样看到使用自动装配配置文件的完整示例
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句