引用 - Maven Profiles
<小时/>我不想在运行时通过命令行参数指定配置文件。因为,如果我在本地更改它,则必须通过 CI 流进行更改。
<小时/>场景:
基本上有两个配置文件“PROD”
和“TEST”
。我已经使用这些注释了方法。基本上,我在不同的配置文件下连接不同的数据库。
虽然测试类用@ActiveProfile("TEST")注释
我使用 mvn clean test-compile failuresafe:integraton-test
运行测试,并使用 mvn springboot:run
运行应用程序
问题:
案例 1:
问题:只有 PROD
相关方法针对 PROD 和 TEST 运行。
如果我不使用@Profile("PROD")
而只使用@Profile("TEST")
并且我使用@ActiveProfiles("测试”)
如引用中指定。上面没有指定任何标志的两个 mvn 命令仅使用未使用配置文件注释的 bean。
案例 2:
问题:PROD
未运行。
如果我在没有任何标志的情况下同时使用 PROD
和 TEST
,则 mvn clean test-compile failuresafe:integraton-test
命令可以完美运行(仅当指定 @ActiveProfile("TEST")
时,否则我必须发送一个标志 -Dspring.profiles.active=TEST
) 但 springboot:run
不起作用,因为它无法获取任何数据库配置并且找不到 Activity 配置文件。
即使我同时使用 PROD 和 @Primary 注释 PROD 配置文件,情况也是如此
令人惊讶的是,即使我提供命令行参数,结果也是一样的。 mvn springboot:run -Dspring.profiles.active=PROD
如果我使用 @ActiveProfiles("PROD") 注释运行这些配置文件的主类
,结果是相同的。
理想场景/预期:
使用mvn test-compile failuresafe:integration-test
运行测试,最好不带标志。 (已经实现,但产品不起作用)
使用 mvn springboot:run
运行 prod,强调无标志。
首选更改:
Java 注解:@Profile
、@ActiveProfile
、@Primary
等注解告诉 Spring-boot 或 maven 使用什么。
POM.xml:设置配置文件以指导 Maven 使用什么内容。
最佳答案
简而言之,我认为您只需将 spring.profiles.active=PROD
添加到 application.properties
我整理了一个示例,打印了 bean 的内容,该内容在 prod ant 测试之间有所不同,希望这会有所帮助。
运行以下代码时,我得到以下输出:
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);
}
}
应用程序属性:
spring.profiles.active=PROD
ProfilesApplicationTests.java:
@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("TEST")
public class ProfilesApplicationTests {
@Test
public void contextLoads() {
}
}
关于java - 如何通过annotations/pom.xml管理maven配置文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43626343/