繁体   English   中英

如何通过annotations / pom.xml管理Maven配置文件?

[英]How to manage maven profiles through annotations/pom.xml?

参考-Maven配置文件


我不想在运行时通过命令行参数指定配置文件。 因为,如果我在本地进行更改,则必须在整个CI流中进行更改。


场景:

基本上有两个配置文件"PROD""TEST" 我已经注释了使用这些方法。 基本上,我在不同的配置文件下连接不同的数据库。

当测试类使用@ActiveProfile("TEST")注释时

我使用mvn clean test-compile failsafe:integraton-test运行mvn clean test-compile failsafe:integraton-test并使用mvn springboot:run运行应用程序


问题:

情况1:
问题:仅针对PROD和TEST运行与PROD相关的方法。

如果我不使用@Profile("PROD")而仅使用@Profile("TEST")而我使用的是@ActiveProfiles("TEST") ,则请参见参考中的指定。 上面没有指定任何标志的两个mvn命令仅使用未用概要文件注释的bean。

情况2:
问题: PROD无法运行。

如果我同时使用PRODTEST而没有任何标志,则mvn clean test-compile failsafe:integraton-test命令可以完美运行(仅当@ActiveProfile("TEST") ,否则我必须发送标志-Dspring.profiles.active=TEST ),但springboot:run无法正常工作,因为它无法获取任何数据库配置,也找不到活动的配置文件。

即使我同时使用PROD和@Primary注释PROD配置文件,情况也是@Primary

令人惊讶的是,即使我提供了命令行参数,结果也是一样的。 mvn springboot:run -Dspring.profiles.active=PROD

如果我注释使用@ActiveProfiles("PROD")运行这些配置文件的主类,则结果是相同的。


理想场景/预期:

要使用mvn test-compile failsafe:integration-test最好不带标志。 (已经实现,但是产品无法正常工作)

要使用mvn springboot:run运行prod mvn springboot:run no标志。


首选更改:

Java注解:注解如@Profile@ActiveProfile@Primary告诉春季启动或Maven使用什么。

POM.xml:设置配置文件以指导Maven使用什么。

简而言之,我认为您只需要向您的application.properties添加spring.profiles.active=PROD

我整理了一个示例,该示例打印出在prodant测试之间不同的bean内容,希望对您有所帮助。

运行以下代码时,我得到以下输出:

mvn spring-boot:run :上下文中的字符串为:PROD

mvn clean test :上下文中的字符串为:TEST

ProfilesApplication.java:

@SpringBootApplication
public class ProfilesApplication implements CommandLineRunner {

    Logger logger = LoggerFactory.getLogger(ProfilesApplication.class);

    @Autowired
    private String profiledString;

    public static void main(String[] args) {
        SpringApplication.run(ProfilesApplication.class, args);
    }

    @Bean
    @Profile("PROD")
    public String prodString() {
        return new String("PROD");
    }

    @Bean
    @Profile("TEST")
    public String testString() {
        return new String("TEST");
    }

    @Override
    public void run(String... args) throws Exception {
        logger.info("The String in the context is: {}", profiledString);
    }
}

application.properties:

spring.profiles.active=PROD

ProfilesApplicationTests.java:

@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("TEST")
public class ProfilesApplicationTests {

    @Test
    public void contextLoads() {
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM