How does SpringBoot use @Value to inject property values in application.properties into static variables

1. Problem description

  If a property is configured in application.properties in the SpringBoot project (if the property name is test.key), we can use the @Value tag in the controller layer or service layer to get the property value, as shown in the following code.

package com.test.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
    
    

    @Value("${test.key}")
    public String testKey;
}

  It is also possible to mark the @Component tag in a Java file, and then use the above @Value tag to obtain the attribute value in the configuration file as well.

  However, if the project needs to inject the attribute value in the configuration file into the static variable (that is, to inject @Value into the variable modified by static), the variable value is found to be null. Sample code is shown below.

	@Value("${test.key}")
    public static String testKey;

  In the above code, static variables are not successfully injected with values.

  @Value can only inject values ​​into ordinary variables. So how to do value injection for static variables?

Two, the solution
  1. Add the @Component annotation to the class name (if the Java file is a controller or service class that has been injected and managed by Spring, you don’t need to add this tag)
  2. Use the setXXX(abc) method and add the @Value annotation to the setXXX(abc) method. The following code example.
package com.test.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class SignUtil {
    
    

    public static String filepath = null;

    @Value("${filepath}")
    public void setFilePath(String filepath) {
    
    
        log.info("静态变量 filepath 赋值:[{}]", filepath);
        SignUtil.filepath = filepath;
    }
}

Remark:

  If it is the set method generated by IDEA for static variables, the static modifier will be added to the method. This is not acceptable, and the static modifier needs to be removed.

Guess you like

Origin blog.csdn.net/piaoranyuji/article/details/126955213
Recommended