java - 将 Spring @Value 传递给静态 @BeforeAll Junit5 方法

标签 java spring

我有这样的情况,我需要设置系统属性,然后再注入(inject)可测试类,因为这个类应该使用这个系统属性进行初始化以进行测试。

为此,我在 @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 来设置系统属性。

有什么解决办法吗?

最佳答案

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")

关于java - 将 Spring @Value 传递给静态 @BeforeAll Junit5 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60053128/

相关文章:

java - 如果aspectj可以单独使用,那么在Spring配置中使用Aspectj有什么好处

java - 如何在 IDE 中将应用程序作为 jar 运行,但将 maven 打包为 war?

java - 如何使用ArrayList在Java Jtable中显示mysql表中的所有数据?

java - 为什么我无法在图像下方显示标签(javafx)?

java - 在其 TreeView 中显示 ITreeContentProvider 的 "input-element"

java - testng 中数据提供者的延迟加载

java - Spring MVC - 在名称为 'servletname' 的 DispatcherServlet 中未找到带有 URI [/HelloWeb/WEB-INF/jsp/hello.jsp] 的 HTTP 请求的映射

java - 构建可重用的 Wicket 组件

spring - Spring 中 Autowiring 的方法 - 下面两种可能的替代方案之间的区别

spring - 如何在我的 Controller 中验证(@Valid)之前检查安全访问(@Secured 或 @PreAuthorize)?