java - 如何为 Spring 的 @PropertySource 注释传递命令行参数?
问题描述
描述:
作为测试开发人员,我想在执行测试之前选择一个特定的属性文件。
问题 :
如何在命令行中调用所需的属性?
我mvn
用来构建我的项目。
主意 :
我在想类似的东西:
~mvn clean verify -Dproperty.source.project1=QA1 -Dproperty.source.project2=QA2
在命令行中处理多个属性选择(如上面的行)会很好,因为这个项目将有多个"propertycontrollers"
代码 :
package com.core.propertycontroller;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
@Configuration
@PropertySource("classpath:application-${env}.properties")
//This project will have Project2PropertyLoader.class, and so on and so forth.
public class Project1PropertyLoader {
public Project1PropertyLoader() { super();}
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
我使用@ContextConfiguration
加载此类。
package com.testrunners;
import com.core.propertycontroller.Project1PropertyLoader;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { Project1PropertyLoader.class } , loader = AnnotationConfigContextLoader.class)
public class EnvironmentTest {
@Autowired
private Environment environment;
@Value("${sample.url}")
private String url;
@Test
public void printUrl() {
System.out.println("Project1PropertyLoader Url via @Value " + url);
System.out.println("Project1PropertyLoader Url via Environment " + environment.getProperty("sample.url"));
}
}
应用程序-QA1.properties
sample.url = https://hello.com
应用程序-QA2.properties
sample.url = https://world.com
更新: 也欢迎替代解决方案。洗耳恭听。谢谢
解决方案
或者,您可以为您的属性设置默认值,如下所示。
@Value("${some.key:stackoverflow.com}")
private String url;
在上面的示例中,stackoverflow.com 将是有效的 url,没有提供任何内容。
推荐阅读
- javascript - 使用类为元素应用样式的 withStyles 错误
- python - 多进程环境中的 cx_Oracle python delete 语句
- python - 从三个文本中计算单词
- reactjs - find 仅返回日期的第一个数据
- java - springboot中的调度器,用于spring批处理的大数据交替
- algorithm - 您如何计算具有多个来源的 Djikstra 热图?
- swift - 如果集合视图位于 UIScrollView 中,是否会重用 UICollectionViewCell?
- angular - Angular:当列表中没有数据时如何显示消息?
- javascript - vite 构建不会在 dist 文件夹中生成 javascript 文件
- javascript - 为什么我的 TextInput 字段在不同的屏幕上表现不同。在本机反应