注入静态成员变量:
方式一:类定义上添加@Component注解, set方法上添加@Autowired注解
@Component public class CacheExtensionsHelper { private static ICacheManager cacheManager; @Autowiredpublic void setCacheManager(ICacheManager cacheManager) { CacheExtensionsHelper.cacheManager = cacheManager; } }
注意:
- 类上面要添加注解@Component, 告诉spring这个类需要扫描
- set方法上添加@Autowired注解, 告诉spring自动注入
- set方法不要添加static关键字,否则自动注入失败
方式二:注解@PostConstruct方式
@Component public class SecurityLogic { @Autowired private PropertyConfigurer propertyConfigurerTmp; private static PropertyConfigurer propertyConfigurer; @PostConstruct public void init() { SecurityLogic.propertyConfigurer = propertyConfigurerTmp; } public static void encrypt(String param) throws Exception { String encryptType=propertyConfigurer.getProperty("encryptType"); //todo } }
@PostConstruct 注解的方法在加载类的构造函数之后执行,也就是在加载了构造函数之后,执行init方法;
(@PreDestroy 注解定义容器销毁之前的所做的操作)这种方式和在xml中配置 init-method和 destory-method方法差不多,定义spring 容器在初始化bean 和容器销毁之前的所做的操作;