Skip to content
Advertisement

Use application.properties in a non-spring injected class

I have a class which is created with new B(this); in this class B I want to use a value from the application.properties. But because (as far as I understand) because it’s not created with Spring it won’t have any injection (I use the @Value annotation)

That is how the class is created:

JavaScript

The class in question:

JavaScript

So my question is the following:

1) How can I use the value in the application.properties file or

2) How can I write B that it is created with Spring?

Some background information:

  • I didn’t wrote the initial code so I don’t want to change too much but want to modify it so it can be maintained better in the future
  • I don’t have that much Spring knowledge and only start getting more and more familiar with it.
  • In point 2) I’m struggling because of the constructorand how to set it via Spring…

Any help would be appreciated

Advertisement

Answer

Here’s an example of using @ConfigurationProperties to bind your application.properties to a POJO.

Say you have a application.properties file like this,

JavaScript

You can create a POJO like this for the above scenario.

(Note: If your spring boot version is lower than 2.2 you might want to annotate this class with @Configuration and @Component as well)

JavaScript

When the spring boot application initializes, it will automatically map values from application.properties into this POJO. If you want to use this, all you have to do is create a variable and mark it with @Autowire

JavaScript

Following up on your question…

Since the class in your example is not managed by spring, and you have to keep it this way for some reason, you can use the following helper class to manually autowire a spring bean in a non spring managed class.

JavaScript

To use this in your class B do the following.

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement