spring中使用@PostConstruct和@PreConstruct注解

时间:2023-03-08 17:28:37
spring中使用@PostConstruct和@PreConstruct注解

1.@PostConstruct说明

被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器调用一次,类似于Serclet的inti()方法。被@PostConstruct修饰的方法会在构造函数之后,init()方法之前运行。

2.@PreDestroy说明

被@PreDestroy修饰的方法会在服务器卸载Servlet的时候运行,并且只会被服务器调用一次,类似于Servlet的destroy()方法。被@PreDestroy修饰的方法会在destroy()方法之后运行,在Servlet被彻底卸载之前。(详见下面的程序实践)

package com.yygx.flowinterface.service.impl;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy; import net.zoneland.uniflow.client.impl.SyncProcessServiceClient;
import net.zoneland.uniflow.client.impl.SyncTaskServiceClient; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository; /**
*
* 流程引擎客户端工具类
* @author wuhda
*
*/
@Repository
public class FlowClientUtil { private final static Logger LOGGER = LoggerFactory.getLogger(FlowClientUtil.class); /**
* 流程类接口客户端
*/
private SyncProcessServiceClient processClient; /**
* 任务类接口客户端
*/
private SyncTaskServiceClient taskClient; @PostConstruct
public void init() {
// 接入系统的账号密码,在流程管理平台(UniflowAdminConsole)上配置
String username = "ehr";
String password = "password"; // Uniflow的服务地址
String endpoint = "http://172.16.92.50:10081/UniflowControlCenter/rest"; // 构建流程类接口客户端
processClient = new SyncProcessServiceClient(username, password);
processClient.setServerAddress( endpoint + "/RestProcessService" ); // 构建任务类接口客户端
taskClient = new SyncTaskServiceClient(username, password);
taskClient.setServerAddress( endpoint + "/RestTaskService" );
} @PreDestroy
public void close() {
System.out.println("close client ...");
// 应用结束是最好关闭客户端(内部有HttpClient的连接池)
processClient.close();
taskClient.close();
} public SyncProcessServiceClient getProcessClient() {
return processClient;
} public void setProcessClient(SyncProcessServiceClient processClient) {
this.processClient = processClient;
} public SyncTaskServiceClient getTaskClient() {
return taskClient;
} public void setTaskClient(SyncTaskServiceClient taskClient) {
this.taskClient = taskClient;
} }