2

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.

Yves
  • 11,597
  • 17
  • 83
  • 180

2 Answers2

2

You need to create a spring managed bean and inject property into that bean. Then you can pass it as a constructor argument to your MyObj.

Here is the example:

@Component // will be instantiated by Spring as a singleton bean
public class MyObjFactory {

    @Value("${apple.price}")
    private int applePrice;

    public MyObj newMyObject() {
        return new MyObj(applePrice);
    }
}

Remember that you should not manually create MyObjFactory using the new operator. Spring instantiates classes marked as @Component during context creation. So you need to inject that factory where you want to use it. You can read more about it here: https://docs.spring.io/spring-framework/reference/core/beans/dependencies/factory-collaborators.html

Yevhenii Semenov
  • 1,587
  • 8
  • 18
0

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);
Chaosfire
  • 4,818
  • 4
  • 8
  • 23