使用Spring注解,在静态方法中注入bean(spring静态注入组件——工具类常用)

如果直接用spring注入静态属性,则会报错,提示@Resource annotation is not supported on static fields,如果又一定要通过spring注入bean,可以采用@PostConstruct注解在某个用来初始化的方法上,注入时注入到另一个不是静态的变量里,然后在初始化方法里面将注入好的变量赋值给静态变量,通过这些操作就给静态变量赋值。

  1. @Component  
  2. public class CodeGenerator { 
  3.     @Resource
  4.     private StringRedisTemplate stringRedisTemplate 
  5.     public static CodeGenerator codeGenerator;  //通过该标签以及该方法实现给static属性注入  
  6.     
  7.     @PostConstruct  
  8.    public void init(){  
  9.         codeGenerator.redisService = this.stringRedisTemplate;  
  10.     }  
  11. }

猜你喜欢

转载自blog.csdn.net/smart_coder/article/details/80858486