环境
idea2018,jdk1.8,
springboot版本:1.5.9.RELEASE
代码下载:
https://github.com/2010yhh/springBoot-demos.git
测试:启动项目后,访问:
http://localhost:8080/springboot-demo2/test1
http://localhost:8080//springboot-demo2/test2
listen的作用:可以在listen中完成一些如数据库、创建、数据库加载等一些初始化操作
@Component
public class StartApplicationListener implements ApplicationListener {
public static AtomicInteger count=new AtomicInteger(0);
protected Logger log = LoggerFactory.getLogger(StartApplicationListener.class);
private ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
//防止重复执行
if (event.getApplicationContext().getParent() == null && count.incrementAndGet()<=1) {
//这里一个定时任务的初始化
this.service.scheduleAtFixedRate(new LogTask(),1000, 1000*60,TimeUnit.MILLISECONDS );
log.info("Listener系统配置加载完成...");
}
}
}
filter的作用:拦截请求,对请求或响应(Request、Response)统一设置,对请求、响应头加密、解密,对请求、响应压缩,过滤掉非法url,做网关转发等
@WebFilter(urlPatterns = "/test1/*", filterName = "indexFilter1")
@Order(Integer.MAX_VALUE-1)
public class MyFilter1 implements Filter {
protected Logger log = LoggerFactory.getLogger(MyFilter1.class);
@Override
public void destroy() {
log.info("----->:indexFilter1 destroy method");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
chain.doFilter(request, response);
log.info("----->:indexFilter1 doFilter method");
}
@Override
public void init(FilterConfig arg0) throws ServletException {
log.info("----->:indexFilter1 init method");
}
}
拦截器作用: * 作用于controller层,拦截到请求,对请求或响应(Request、Response)统一设置 * 进行逻辑判断,如用户是否已经登陆、有没有权限访问该页面等 和filter的作用有些类似,但二者又有不同的应用场景。
public class MyInterceptor implements HandlerInterceptor {
protected Logger log = LoggerFactory.getLogger(MyInterceptor.class);
//在请求处理之前进行调用(Controller方法调用之前
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
log.info("preHandle被调用");
return true; //如果false,停止流程,api被拦截
}
//请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
log.info("postHandle被调用");
}
//在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
log.info("afterCompletion被调用");
}
}
aop的作用:横切面,代表的是一个普遍存在的与业务关系不大的却各个模块共有功能 * 横切关注点:经常发生在核心关注点的多处,而各处都基本相似。比如权限认证、日志、方法耗时 * 、事务处理
@Aspect //声明切面
@Component
public class LogAspect {
protected Logger log = LoggerFactory.getLogger(LogAspect.class);
//定义横切点,标记方法
@Pointcut("execution(* com.ctg.test.controller..*.*(..))")
public void webLog(){}
//前置通知,切点之前执行
@Before("webLog()")
public void deBefore(JoinPoint joinPoint) throws Throwable {
// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 记录下请求内容
log.info("URL : " + request.getRequestURL().toString());
log.info("HTTP_METHOD : " + request.getMethod());
log.info("IP : " + request.getRemoteAddr());
log.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
log.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
}
//切点执行成功之后执行
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfterReturning(Object ret) throws Throwable {
// 处理完请求,返回内容
log.info("方法的返回值 : " + ret);
}
//后置异常通知,切点抛出异常后执行
@AfterThrowing("webLog()")
public void throwss(JoinPoint jp){
log.info("方法异常时执行.....");
}
//后置最终通知,final增强,不管是抛出异常或者正常退出都会执行;切点执行之后执行
@After("webLog()")
public void after(JoinPoint jp){
log.info("方法最后执行.....");
}
}
自定义注解可以避免代码的冗余,无侵害
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
@Inherited
public @interface MethodTime {
//自定义属性
}