0

到目前为止,我已经设法避免为我的 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);
         }
     ...
 }

任何帮助将不胜感激。

干杯,斯科特。

4

1 回答 1

1

愚蠢的我,校对这个问题我注意到一个糟糕的复制和粘贴工作意味着两个 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

希望这对其他人有所帮助,因为我还没有看到像我在网络上其他地方所做的那样使用自动装配配置文件的完整示例

于 2016-03-29T13:37:56.150 回答