SpringBoot stepped in when using @Value read configuration files pit

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/Mr__Viking/article/details/84558251

Recently doing some projects with spingboot, today java Bean wanted to initialize the variables to value through a configuration file variable in the time to build the project, springboot is developed based annotation Well, it took a @Value comment to inject the configuration file variable. But in this place I trod several pits, so record it, so as not to make the same mistake the next time.

1. @ Value Notes can not be injected into the static keyword modified variables above

Originally, I wanted to write a static property as a property profile, external call to the convenience, but @Value comment does not support this operation ~, online search a bit, saying that @Value comment can not be used in static variables above, I also verified behind, indeed can not be injected into a static field to the top.

2. When calling a class member properties in the no-argument constructor @Value did not work

code show as below:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;



/**
 * Created by viking on 2018/11/26
 * 自定义配置类
 */
@Component
public class MyConfiguration {

    @Value("${config.file}")
    private String fileName;

    public MyConfiguration(){
        System.out.println("读取到的配置文件名称:"+fileName);
    }
}

application.properties configuration variables:

config.file=MyConfiguration.properties

Then look at the results when the debug:

Direct is a null value, in accordance with the initialization sequence java class, the member variable initialization is certainly in preference to the constructor, @ Value annotation does not play any role, because @Value annotations are only acting after the constructor to initialize. So call the variables in the constructor and when no value.

3. Open the right way: in the class constructor after the initialization is complete to call

When spring is here, I used @PostContruct annotation, this annotation is applied to the method, indicating that the method will be executed after the constructor method execution is completed.

Let's look at operating results:

Now there is worth it.

This article is the original author, if there is doubt or where there is an error in the text of the description herein, we welcome message pointed out!

 

Guess you like

Origin blog.csdn.net/Mr__Viking/article/details/84558251