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[]