Case 1: Spring’s injection of static variables is null

The case code is as follows:

@Component
public class HelloWorld {
   /** * Error case: Static variables cannot be injected with attribute values */
    @Value("${hello.world}")
    public static String HELLO_WORLD;
}
Copy the code

Solution 1: The @value annotation is added to setter methods

@Component
public class HelloWorld {
    public static String HELLO_WORLD;
    
    @Value("${hello.world}")
    public void setHELLO_WORLD(String HELLO_WORLD) {
        this.HELLO_WORLD = HELLO_WORLD; }}Copy the code

Solution 2: @postconstruct annotations

Since the @postconstruct annotation decorates methods before static variable assignments are ordered after constructors, we can use the annotation to resolve static variable property injection failures:

@Component
public class HelloWorld {
    public static String HELLO_WORLD;
  
    @Value("${hello.world}")
    public static String helloWorld;
    
    @PostConstruct
    public void init(a){
        // Assign a value to the static variable (the value is the value of the hello.world field obtained from the Spring IOC container)
        HELLO_WORLD = this.helloWorld; }}Copy the code

Case 2: Using the Bean object in the Spring container in the constructor, the result is empty

The business scenario assumes:

Eg: I need to call the service layer interface (UserService) to execute a method (sayHello) when a class (HelloWorld) is loaded. Some students might do this by calling the sayHello() function of the UserService in the constructor. But this can lead to some error exceptions, as shown in the following example.

The error demonstration code is as follows:

@Component
public class HelloWorld {
     
   /** * UserService injects */
    @Autowired
    private UserService userService;

    public HelloWorld(a){
       // null pointer exception: If userService is used directly, the value of the property is null, and a null member variable calls sayHello(), NullPointException is a normal exception.
       userService.sayHello("hello tiandai!"); }}Copy the code

Solution: @postconstruct annotation

Since the @PostConstruct annotation decorates a method whose life cycle is after the constructor call and before the Spring property value is injected, the annotation addresses this business requirement nicely, as follows:

@Component
public class HelloWorld {
     
   /** * UserService injects */
    @Autowired
    private UserService userService;

    public HelloWorld(a){}@PostConstruct
    public void init(a){
       userService.sayHello("hello tiandai!"); }}Copy the code

About this part of the problem, there are some strange usage, refer to the article: blog.csdn.net/dream199903…