@PostConstruct注解
被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器调用一次,类似于Serclet的inti()方法。被@PostConstruct修饰的方法会在构造函数之后,init()方法之前运行。
@Component
public class JedisPoolWrapper {
private JedisPool jedisPool = null;
@Autowired
private Parameters parameters;
//redis的一些基础的配置信息,创建放在一个类中,可以统一管理
@PostConstruct
public void init() throws BikeException {
try {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(parameters.getRedisMaxTotal());
config.setMaxIdle(parameters.getRedisMaxIdle());
config.setMaxWaitMillis(parameters.getRedisMaxWaitMillis());
jedisPool = new JedisPool(config,parameters.getRedisHost(),parameters.getRedisPort(),2000,parameters.getRedisAuth());
} catch (Exception e) {
log.error("Fail to initialize jedis pool", e);
throw new BikeException("Fail to initialize jedis pool");
//自定义异常,log输出到文件
}
}
//这样启动的时候可以直接get到redispool
public JedisPool getJedisPool() {
return jedisPool;
}
}
@PreDestroy
被@PreDestroy修饰的方法会在服务器卸载Servlet的时候运行,并且只会被服务器调用一次,类似于Servlet的destroy()方法。被@PreDestroy修饰的方法会在destroy()方法之后运行,在Servlet被彻底卸载之前