# SpringBoot two ways to inject static member variables

SpringBoot injects static member variables in two ways


Add @Autowired annotation to set method, add @Component annotation to class definition

  • The static keyword of the setter method of the static variable should be removed, otherwise the injection will fail.
@Component
public class RedisClient {
    
    

    private static Logger logger= Logger.getLogger(String.valueOf(RedisClient.class));

    private static RedissonClient redissonClient;

    @Autowired(required = true)
    public void setRedissonClient(RedissonClient redissonClient){
    
    
        RedisClient.redissonClient=redissonClient;
        logger.info("redisclinet注入完成!");
    }

    public static void setList(){
    
    
        redissonClient.getList("one").add("two");
    }
}

@PostConstruct way to achieve

  • The method annotated by @PostConstruct is executed after the constructor of the class is loaded, that is, after the constructor is loaded, the init method is executed. This method is similar to configuring the init-method and destruction-method methods in xml, and defines the operations that the spring container does before the bean is initialized and the container is destroyed.
@Component
public class RedisClient1 {
    
    
    
        @Autowired
        private static RedissonClient redissonClient;

        private static RedisClient1 redisClient1;

        @PostConstruct
        public void init() {
    
    
            redisClient1 = this;
            redisClient1.redissonClient= this.redissonClient;
        }
}

Guess you like

Origin blog.csdn.net/qq_37248504/article/details/108763378