spring的监听器和缓存


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 = ((MethodSignature)point.getSignature()).getParameterTypes();  
        // 获取IP  
        HttpServletRequest request = ( (ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();  
        String ip = request.getRemoteHost();  
        String[] operation;  
        try {  
            // 得到访问的方法对象  
            Method method = className.getMethod(methodName, argClass);  
            // 判断是否存在@OperationLog注解  
            if (method.isAnnotationPresent(OperationLog.class)) {  
                OperationLog annotation = method.getAnnotation(OperationLog.class);  
                // 取出注解中的信息  
                operation = annotation.value();  
                if (operation.length != 3) {  
                    return;  
                } else {  
                    logService.addOperateLog(ip, operation[0], Long.parseLong(OperateType.getNo(operation[1]).toString()),operation[2]);  
                }  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
    @After("dbPointCut()")  
    public void afterSwitchDS(JoinPoint point){  
        // 操作结束  
    }  
}  
​

Springboot中使用catche缓存机制

一、引入依赖

<dependency>  
      <groupId>org.springframework.boot</groupId>  
      <artifactId>spring-boot-starter-cache</artifactId>  
</dependency>

二、 @EnableCaching开启缓存//@MapperScan(basePackages = {"com.wang.cache.dao"})

_@SpringBootApplication  
 @EnableCaching  // 开启缓存注解  
public class SpringbootCacheApplication {  
    public static void main(String[] args) {  
        SpringApplication.run(SpringbootCacheApplication.class, args);  
    }_


@Service  
@Transactional(readOnly = true)  
public class IndexService {  
​  
  @Autowired  
  private IndexMapper indexMapper;  
​  
  /**  
   * 将方法的运行结果进行缓存,以后要相同的数据就直接获取  
   * CstcheManage 管理多个catche组件,每个缓存组件都有一个唯一的名字  
   * <p>  
   * 几个属性:  
   * catcheManage/value:指定缓存组件的名字  
   * key:缓存数据使用的key 默认是方法的参数的值   key id=1 ,value 方法的返回值  
   * 也可以使用Espl表达式来使用  
   * <p>  
   * keyGenerator:key生成器,可以自己指定key的生成器的组件id   key/keyGenerator二者选一  
   * <p>  
   * catcheManage:指定缓存管理器,或者catchResolve指定获取解析器  
   * condition:指定符合条件的情况下菜缓存  指定条件  "#id>1"  
   * unless:否定缓存,当unless指定的条件为true 方法的返回值就不会被缓存;可以获取结果进行判断  unless="#result"==null  
   * sync:是否使用异步模式  
   *  
   *  
   * @return  
   */  
​  
  @Cacheable(cacheNames = "indexMapper.getAll()",condition = "#")  
  public List<Index> getAll() {  
    return indexMapper.getAll();  
  }  
}


原文链接:https://www.cnblogs.com/fmhh/p/13520456.html