spring的元件
阿新 • • 發佈:2020-08-17
Springboot中使用監聽器
一、傳統的方法(configguration)
@Slf4j
public class MyListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
log.info("web專案的啟動{} 一開始就啟動",sce.getServletContext());
System.err.println("web專案的啟動{}");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
log.info("web專案的關閉{}.........................");
System.err.println("web專案的關閉{}............................");
}
}
把監聽器給springboot
@Configuration
public class ListenerConfig {
@Bean
public ServletListenerRegistrationBean myListener() {
ServletListenerRegistrationBean<MyListener> registrationBean = new
ServletListenerRegistrationBean<>(new MyListener());
return registrationBean;
}
}
二、基於註解的實現
@WebListener
@Component
public class LoginListener implements ServletRequestListener {
@Override
public void requestInitialized(ServletRequestEvent servletRequestEvent) {
System.out.println("---------------------------->請求建立");
}
@Override
public void requestDestroyed(ServletRequestEvent servletRequestEvent) {
System.out.println("---------------------------->請求銷燬");
}
}
最後,在啟動類加上註解@ServletComponentScan(basePackages = "com.apl.pgs.listener.*"),開啟監聽器。
basePackages =監聽器的 包名+類名 。可以開啟一個或多個。
這樣,監聽器就配置完成了,具體業務邏輯可以在監聽器做處理了。
Springboot中使用列舉實現的切面:
一、基於註解實現的切面
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface OperationLog {
String[] value();
}
//列舉類
public enum OperateType {
OPERATE_TYPE_1(1, "新增"),
OPERATE_TYPE_2(2, "修改"),
OPERATE_TYPE_3(3, "刪除"),
OPERATE_TYPE_4(4, "查詢"),
OPERATE_TYPE_5(5, "停用/啟用"),
OPERATE_TYPE_6(6, "釋出"),
OPERATE_TYPE_7(7, "上傳"),
OPERATE_TYPE_8(8, "匯入"),
OPERATE_TYPE_9(9, "匯出"),
OPERATE_TYPE_10(10, "作廢"),
OPERATE_TYPE_11(11, "排序");
private Integer no;
private String name;
OperateType(Integer no, String name) {
this.no = no;
this.name = name;
}
public static Integer getNo(String name) {
for (OperateType o : OperateType.values()) {
if (o.getName().equals(name)) {
return o.getNo();
}
}
return null;
}
public Integer getNo() {
return no;
}
public void setNo(Integer no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
//切面類的方法
@Aspect
@Component
public class OperationLogAspect {
@Autowired
private JdOperateLogService logService;
@Pointcut("@annotation(OperationLog)")
public void dbPointCut() {
}
@Before("dbPointCut()")
public void beforeSwitchDS(JoinPoint point){
// 獲得當前訪問的class
Class<?> className = point.getTarget().getClass();
// 獲得訪問的方法名
String methodName = point.getSignature().getName();
// 得到方法的引數的型別
Class[] argClass