第一步:写注解@Component 使当前类成为一个bean对象。(@Controller,@service都行)
第二步:写个static的变量
第三步:写个@PostConstruct注解注解注释的方法,在这个方法里,将自动注入的值赋值给定义的static变量
第四步:static变量替代自动注入在static方法里面使用
复制代码
@Component
public class DSHWechatApiUtil extends DSHBaseController {
@Autowired
private IThirdPartyAuthDao thirdPartyAuthDao;
@Autowired
private static IThirdPartyAuthDao staticThirdPartyAuthDao;
@PostConstruct
public void init() {
staticThirdPartyAuthDao = thirdPartyAuthDao;
}
public static JSONObject getAuthorizerToken(String componentAccessToken, String authorizerAppid, String authorizerRefreshToken) {
JSONObject returnObject = new JSONObject();
try {
if (DSHUtils.isEmpty(componentAccessToken)) {
componentAccessToken = staticThirdPartyAuthDao.selectWechatValue(DSHConstants.WECHAT_PARAMS.COMPONENT_ACCESS_TOKEN);
}
} catch (Exception e) {
e.printStackTrace();
}
return returnObject;
}
}
复制代码
@PostConstruct注解作用:是Java EE 5引入的注解,Spring允许开发者在受管Bean中使用它。当DI容器实例化当前受管Bean时,@PostConstruct注解的方法会被自动触发,从而完成一些初始化工作。
注意:
只有一个方法可以使用此注释进行注解;
被注解方法不得有任何参数;
被注解方法返回值为void;
被注解方法不得抛出已检查异常;
被注解方法需是非静态方法;
此方法只会被执行一次;