Spring Aop自定义注解用在Controller层

  • Post author:
  • Post category:其他


前提项目用的框架是SpringMVC。


切面类:

@Aspect
//@Component 把这个注掉是为了不让Spring中扫描,应该让SpringMVC扫描
public class SysLogAop {
    @Pointcut("@annotation(com.thinkgem.jeesite.common.annotation.SysLogAnnotation)")
    public void requestPointcut(){}


    @Around("requestPointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable{
        long startTime = System.currentTimeMillis();
        Object[] objArr = point.getArgs();
        Object obj = point.proceed();
        long endTime = System.currentTimeMillis();
        System.out.println("响应时间:"+(endTime-startTime));
        return obj;
    }
}


自定义注解:

@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SysLogAnnotation {
   String title();
}


Spring-mvc.xml:

添加aop的schema

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc"
      xmlns:aop="http://www.springframework.org/schema/aop"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
      http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
      http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
    
    <description>Spring MVC Configuration</description>
   
   
   <!-- 使用Annotation自动注册Bean,只扫描@Controller -->
   <context:component-scan base-package="com" use-default-filters="false"><!-- base-package 如果多个,用“,”分隔 -->
      <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
   </context:component-scan>
    
   <!--扫描Controller的自定义注解 并注入切面,注意切面需要手动注入-->
   <aop:aspectj-autoproxy/>
   <bean id="sysLogAop" class="com.log.aop.SysLogAop"></bean>

</beans>

Controller层使用

@SysLogAnnotation(title="试题标引审核管理-公共题标识")
@RequestMapping("isPublic")
public String isPublic( Question question, Model model){
   model.addAttribute( "userId", UserUtils.getUser().getId() );
   return "modules/ykd/question/question_isPublic_index";
}



版权声明:本文为babysteps原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。