这里实例是,如果系统出现异常,就需要在LogUtil类中发送短信。就需要引用到CellMessageService。但LogUtil类中的方法都是静态方法。
@Autowired
private static CellMessageService messageService;
如果直接这样静态引用属性,那么这个属性不管怎么调用都是null。 这里就会涉及到静态类型的使用: 1.静态属性会随着类加载而加载 2.静态方法里不能直接访问非静态成员变量。
所以遇到这种情况就可以用到@PostConstruct注解
@PostConstruct注解是Java自己的注解,不是Spring提供的。
应用:在静态方法中调用依赖注入的Bean中的方法。
@PostConstruct该注解被用来修饰一个非静态的void()方法。被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行。
通常我们会是在Spring框架中使用到@PostConstruct注解 该注解的方法在整个Bean初始化中的执行顺序:
Constructor(构造方法) -> @Autowired(依赖注入) -> @PostConstruct(注释的方法)
public class LogUtils {
private static CellMessageService messageService = new CellMessageService();
//private static CellMessageService messageService;
@Autowired
private CellMessageService cellMessageService;
@PostConstruct
public void init(){
messageService = cellMessageService;
}
public static void sendMessage(Exception ex){
if(null!=ex){
try {
//出现异常发送短信通知
messageService.send("131****8308",null,"XXX系统出现异常!","太阳王",null);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
然后测试debug的时候就能成功实现了