New to Spring...
I am trying to override a parameter which is read from app.properties
at runtime.
For various reasons, I have to use AnnotationConfigApplicationContext
to access the bean.
Here is the sample code
@ComponentScan(basePackages = {
"my.pkg1.*",
"my.pkg2.*"
}
@PropertySource("classpath:app.properties")
public class MainApplication {
public static void main(String[] args) {
try {
log.info("ARGS [" + Arrays.asList(args).stream().collect(Collectors.joining()) + "]");
final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainApplication.class);
ConfigurableEnvironment env = context.getEnvironment();
env.setRequiredProperties("prop1=value2"); //hard coded here for ease
context.setEnvironment(env);
context.getBean(MyService.class).doSomeWork();
} catch (Exception t) {
log.error("Application failed", t);
}
}
}
Let's say, in my app.properties
, I have some thing like
prop1=value
I would like to override prop1=value2 but my approach as displayed above does not seem to work.
Couple of other things I looked at:
- I thought it would be as easy as: Spring: overriding one application.property from command line. But that did not work, maybe because this is not a spring-boot app?
- This other approach doesn't really work because I don't really want to pass a constructor param.
- I don't really understand this approach