@PostConstruct和@PreDestroy使用纪要
背景: 公司项目中用需要抽离公共代码,但是发现service层对象无法通过@Autowired注入到,
最终获取到null的对象. 起始为了解决该问题将对应的对象设置为了类的成员变量(公量),后
来项目优化有人用到了@PostConstruct这个注解. 此景之下经过研究和项目应用,特此写下
本篇博文,以供后续参考.
说明: 主要围绕PostConstruct进行讲解.
特点: 这两个注解都是被用来修饰一个非静态的void()方法.
作用:
: 被@PostConstruct修饰的方法会在服务器加载Servle的时候运行,并且只会被服务器执行一次.
(@PostConstruct在构造函数之后执行,init()方法之前执行)
: @PreDestroy在destroy()方法执行执行之后执行.
语法:
// 1.
@PostConstruct
Public void someMethod() {
// Codding...
}
// 2.
public @PostConstruct void someMethod(){
// Codding...
}
package com.dto;
import com.XxService;
@Component
public class TestUtil {
@Autowired
private XxService xxService;
public static TestUtil testUtil;
@PostConstruct
public void init() {
testUtil = this;
}
/**
* List<xx>
*
* @param xxx
* @return
* @throws Exception
*/
public static xxx ladding(String xx) throws Exception {
xxx xName = xxService.list();
return xName;
}
}