简体   繁体   中英

Spring Boot - Cannot read application.yml values from instantiated object

I'm trying to read some setting values from application.yml using the @ConfigurationProperties annotation.

An instantiated object of the class TestClass uses the properties class, so I added the @Configurable annotation, but the properties always be null and it causes NullpointerException.

The properties class:

@ConfigurationProperties
@Getter
@Setter
public class Properties {
    
    private String setting;

}

And the object which uses the properties:


@Configurable
public class TestClass{

    @Autowired
    private Properties properties;

    void print(){
        System.out.println(properties.getSetting());
    }
}

If I call the print method, NullPointerException will be occurred:

TestClass testClass = new TestClass();
testClass.print();

Am I missing something?

Short Answer:

Find the class that is annotated with @SpringBootApplication and add there also the annotation @EnableConfigurationProperties(Properties.class)

@SpringBootApplication
@EnableConfigurationProperties(Properties.class)
public class ServiceLauncher {

Explanation:

@ConfigurationProperties does not register the class that brings this annotation as a spring bean. It is only used so that Spring can read the properties with some meta configured information (ex prefix = "some.prop.prefix" ).

If you wish to use this class as a spring bean (ex via @Autowired ) you need to combine the above annotation with @EnableConfigurationProperties which then says to spring that this class must become a spring bean.

Another workaround:

You could also instead just use the @Component on the Properties class and that would be enough without the need of @EnableConfigurationProperties but the later is better practice to be used.

@Component
@ConfigurationProperties
@Getter
@Setter
public class Properties {

Edit: After clarrified in the comments there is also another mistake in this code. You should replace @Configurable with @Configuration . The first one does not create a spring bean on the class that is placed!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM