I'm using Springboot to develop a web server and I need to add some custom configurations for it. So I put the config into resources/application.properties
as below:
apple.price=1
In some function I need to get the config.
class MyObj {
@Value
private int applePrice;
}
This is not working because MyObj
is not managed by Springboot.
But I couldn't add any annotation like @Component
for the class MyObj
because the objects of MyObj
is initialized manually: MyObj obj = new MyObj();
So it seems that I need to get the injected bean in an unmanaged object.
I'm a Springboot newbie, please help me on this issue.
If you don't have access to the application context or other beans, you can keep static reference to AutowireCapableSpringBeanFactory
to manually autowire manually created objects. You could do it as in this answer, for example.
Then autowire the instances like this:
MyObj obj = new MyObj();
ApplicationContextHolder.autowireBean(obj);