首页 > 解决方案 > 如何为 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

更新: 也欢迎替代解决方案。洗耳恭听。谢谢

标签: javaspringspring-bootmaven

解决方案


或者,您可以为您的属性设置默认值,如下所示。

@Value("${some.key:stackoverflow.com}")
private String url;

在上面的示例中,stackoverflow.com 将是有效的 url,没有提供任何内容。


推荐阅读