@Value injection problems fail

1. The first step to detect syntax is correct

@Value("${test}")
private String test;

2. Secondly, if there is configured to detect the configuration file

url=test
username=username
password=password

3. The third step is to detect whether an increase @Component comment

In the spring, the use of annotations spring, then you need to use spring to manage objects, not themselves new, otherwise it will lead to failure.

@Component    // the class to spring object-managed 
public  class DbUtils {

    @Value("${url}")  
    private String url;
    @Value("${username}")  
    private String username;
    @Value("${password}")  
    private String password;

}

4. The fourth step of writing mode detection code

Do no longer participate in the constructor, the operation of the new objects. Otherwise it will cause @Value comment failed. (I stepped on this step is to pit).

   @PostConstruct initial context can be used to initialize notes, he will finish the spring loading information, call and call only once.

5. @ Value can not be injected into the static properties

@Value use directly on the static properties can not be injected content !!! this way will always be null.

The reason
was found @value not be injected directly to the value of the static property, spring does not allow / do not support the value injected into the static variable; spring support set injection method, we can use non-static setter method injection static variables, and classes must use @Value .. to pay a spring is managed just as @Autowired may not inject the same
details: https://blog.csdn.net/sqlgao22/article/details/100100314

Improve

Use setter methods assign attributes and setter methods can not have a static

idea of ​​the method will be automatically generated static, you need to be deleted manually.

@Component    // the class to spring object-managed 
public  class DbUtils {

    private static String url;
    private static String username;
    private static String password;

    @Value ( "{$ url}")   // delete the static 
    public  void setUrl (String url) {
        DBUtils.url = url;
    }
    @Value("${username}")
    public void setUsername(String username) {
        DBUtils.username = username;
    }
    @Value("${password}")
    public void setPassword(String password) {
        DBUtils.password = password;
    }
    // see if injecting 
    public  static  void GET () {
        System.out.println("=====url====="+url);
        System.out.println("=====username====="+username);
        System.out.println("=====password====="+password);
    }
}

test

    @RequestMapping("/get")
    @ResponseBody
    public String get() {
        DBUtils.get();
        return "get";
    }

 

After the test output:


Here Insert Picture Description


Successfully injected attributes.

 

Article reprint to: https://blog.csdn.net/sqlgao22/article/details/100096348

Guess you like

Origin www.cnblogs.com/nhdlb/p/11741228.html