Issue
I use Azure KeyVault to store some values. I need to get this values (e.g. mysql-uri or client-secret) and create new properties in application.yml (and application-local.yml). First of all, I tried to create Configuration-class with @Bean like getDataSource to create connection to database and I did it successfully, but I need to add other fields as well, such as 'oauth.client.secret'.
So I tried to get values and create 'properties' in main-class, but @Value couldn't be static and this solution throws NPE. I tried to create new Configuration-class and get properties from it and then pull it into SpringApplicationBuilder
, but I need ApplicationContext (so SpringApplication.run
will be called) to get an instance (bean) of this class with values...
I don't know what to do next, I'm stuck. Ready to rewrite and show any solution you need.
UPDATE 1:
@Value("${secret}")
private String clientSecret;
public static void main(String[] args) {
new SpringApplicationBuilder(DefaultApplication.class).properties(getProperties()).run(args);
}
@NotNull
private static Properties getProperties() {
Properties properties = new Properties();
properties.put("oauth.client.secret", Objects.requireNonNull(clientSecret));
return properties;
}
clientSecret with error: Non-static field 'clientSecret' cannot be referenced from a static context.
Solution
You can try this way of injecting properties. This uses a simpler convenience class SpringApplication
instead of SpringApplicationBuilder
.
MainClass.java
@SpringBootApplication
public class MainClass {
public static void main(String... args) {
SpringApplication.run(MainClass.class, args);
}
}
The application.yaml will be automatically loaded into the context by Spring Boot (unless you have configured against it). Properties can be reused, redefined (using profiles) and system/env variables can be used as well.
NOTE Spring configurations are pretty flexible and powerful. Please read this documentation https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.external-config
application.yaml
app:
name: Demo
oauth:
client:
secret: ${app.name} // This will have "Demo"
env:
path: ${SOME_ENV_VAR} // This will take SOME_ENV_VAR from env variable
SomeService.java
@Service
public class SomeService {
@Value("${app.name})
private String appName;
public void printAppName() {
log.info(appName); // will log the appname
}
}
Answered By - aksappy