Java 如何通过annotations/pom.xml管理maven概要文件?
参考-Java 如何通过annotations/pom.xml管理maven概要文件?,java,maven,spring-boot,maven-profiles,Java,Maven,Spring Boot,Maven Profiles,参考- 我不想在运行时通过命令行参数指定概要文件。因为,如果我在本地更改它,那么必须在考虑CI流的情况下进行更改 场景: 基本上有两个配置文件“PROD”和“TEST”。我已经使用这些方法对方法进行了注释。基本上,我在不同的配置文件下连接不同的数据库 而测试类则用@ActiveProfile(“test”) 我使用mvn clean test运行测试编译failsafe:integraton测试并使用mvn springboot:run运行应用程序 问题: 案例1: 问题:只有PROD相关
我不想在运行时通过命令行参数指定概要文件。因为,如果我在本地更改它,那么必须在考虑CI流的情况下进行更改
场景: 基本上有两个配置文件
“PROD”
和“TEST”
。我已经使用这些方法对方法进行了注释。基本上,我在不同的配置文件下连接不同的数据库
而测试类则用@ActiveProfile(“test”)
我使用mvn clean test运行测试编译failsafe:integraton测试
并使用mvn springboot:run运行应用程序
问题: 案例1:
问题:只有
PROD
相关方法可用于PROD和TEST
如果我不使用@Profile(“PROD”)
,只使用@Profile(“TEST”)
,并且我使用了参考中指定的@ActiveProfiles(“TEST”)
。没有在上面指定任何标志的两个mvn命令都只使用不带概要文件注释的bean。案例二:
问题:
PROD
未运行
如果我在没有任何标志的情况下同时使用PROD
和TEST
,mvn clean TEST compile failsafe:integraton TEST
命令运行良好(只有在指定@ActiveProfile(“TEST”)
时,否则我必须发送标志-Dspring.profiles.active=TEST
)但是springboot:run
不起作用,因为它无法获取任何数据库配置,也找不到活动配置文件
即使我同时使用PROD和@Primary
令人惊讶的是,即使我提供了命令行参数,结果也是一样的<代码>mvn springboot:run-Dspring.profiles.active=PROD
如果我用@ActiveProfiles(“PROD”)
注释运行这些配置文件的主类,结果是相同的。理想情景/预期: 要使用
mvn测试运行测试,请编译故障保护:集成测试最好不带标志。(已实现,但prod不工作)
要使用mvn springboot运行prod:运行
强调无标志
更可取的变化: Java注释:注释,如
@Profile
,@ActiveProfile
,@Primary
,告诉Spring boot或maven使用什么
POM.xml:设置用于指导maven使用的配置文件。简而言之,我认为您只需要将
spring.profiles.active=PROD
添加到您的应用程序中。属性
我把一个例子放在一起,它打印了不同于prod-ant测试的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() {
}
}
如果您使用的是
mvn clean test compile failsafe:integraton test
,您似乎还不了解生命周期。为什么不干脆mvn clean verify
(如果您正确配置了故障保护插件)…除此之外,@Profile仅用于spring配置文件,而不用于maven配置文件…mvn verify
也运行单元测试。我只想运行集成测试。您正在混合Spring配置文件和Maven配置文件。两者都是不同的东西,也有不同的用途。@M.Deinum但是,@Profile
和@ActiveProfile
在测试中起作用。效果很好。谢谢