【问题标题】:Pass Spring @Value into static @BeforeAll Junit5 method将 Spring @Value 传递给静态 @BeforeAll Junit5 方法
【发布时间】:2020-02-04 08:13:38
【问题描述】:

我有这种情况,我需要在注入可测试类之前设置系统属性,因为这个类应该用这个系统属性初始化以进行测试。

为此,我在@BeforeAll 方法(即static)中运行系统变量设置:

    @Autowired
    private MyService myService;  

    @BeforeAll
    public static void init(){
        System.setProperty("AZURE_CLIENT_ID", "someId");
        System.setProperty("AZURE_TENANT_ID", "someId");
        System.setProperty("AZURE_CLIENT_SECRET", "someSecret" );
    }

而且效果很好。

但是现在我想从 application.yaml 中读取这个属性,比如:

    @Value("clientId")
    private String clientId;

    @BeforeAll
    public static void init(){
        System.setProperty("AZURE_CLIENT_ID", clientId);
        System.setProperty("AZURE_TENANT_ID", tenantId);
        System.setProperty("AZURE_CLIENT_SECRET", someSecret);
    }

问题是我不能从静态方法中引用非静态的,我肯定需要先运行@BeforeAll 来设置系统属性。

有什么解决办法吗?

【问题讨论】:

标签: java spring


【解决方案1】:

How to assign a value from application.properties to a static variable? 在第二个答案中提出的解决方案对我有用。刚刚添加了

public class PropertiesExtractor {
private static Properties properties;
static {
    properties = new Properties();
    URL url = PropertiesExtractor.class.getClassLoader().getResource("application.properties");
    try{
        properties.load(new FileInputStream(url.getPath()));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public static String getProperty(String key){
    return properties.getProperty(key);
}

}

然后在我的静态代码中 @BeforeAll 得到了所有需要的属性

PropertiesExtractor.getProperty("clientId")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-01
    • 2019-08-11
    • 2015-05-08
    • 1970-01-01
    相关资源
    最近更新 更多