Reputation: 1817
I have such case, I need to set system properties, before I inject testable class, because this class should be init with this system property for test.
To do this I run setting of system vars in @BeforeAll
method which is 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" );
}
And it works perfectly fine.
But now I want to read this property from application.yaml, like :
@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);
}
Problem is that I cannot reference non-static from static method and I definitely need to run @BeforeAll
first to set System properties.
Any solution for this?
Upvotes: 6
Views: 2616
Reputation: 1817
Solution proposed in How to assign a value from application.properties to a static variable? in second answer worked for me. Just added
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);
}
}
And then in my code in static @BeforeAll got all need properties with
PropertiesExtractor.getProperty("clientId")
Upvotes: 3