spring aop

作者: 虾米爱螃蟹 | 来源:发表于2018-05-23 21:31 被阅读0次

一、Spring Aop 表达式:

(1)、execution表达式详解:

execution(* com.sample.service.impl..*.*(..))

解释如下:

execution():表达式的主体。(不可省略)

第一个”*“符号 :表示返回值的类型任意。(不可省略)

com.sample.service.impl  :AOP所切的服务的包名,即,我们的业务部分。(可省略)

包名后面的”..“:表示当前包及子包。(可省略)

第二个”*“:表示类名,*即所有类。(可省略)

第三个“*”:表示任何方法名,括号表示参数,两个点表示任何参数类型。(不可省略)

(..)  :括号表示参数,两个点表示任何参数类型。(不可省略)

(2)、其它表达式语法可以参考spring官方文档:https://docs.spring.io/spring/docs/2.0.x/reference/aop.html#aop-ataspectj

二、Spring Aop Examples

依赖jar包:aspectjweaver-1.8.13.jar、aspectjrt-1.8.13.jar、spring-aop-3.2.9.RELEASE

(1)、spring.xml配置

(2)、定义切面

@Component

@Aspect

public class TimeServiceAspect {

   @Pointcut("execution(* com.weiming.mall.web.service..*.*(..))")

    public void pointcut() {}

  @Before("pointcut()")

   public void before(JoinPoint joinPoint) {

        long startTime = System.currentTimeMillis();

        System.out.println("service:"+startTime);

    }

  @After("pointcut()")

   public void after(JoinPoint joinPoint) {

        long endTime = System.currentTimeMillis();

        System.out.println("service:"+endTime);

    }

}

(3)、定义时间接口

public interface TimeService {

        public void time();

}

(4)、定义接口实现类

@Service

public class TimeServiceImpl  implements TimeService{

   public void time() {

       System.out.println("=====123");

    }

}

(5)、测试

@Controller

@RequestMapping("/test")

public class TestController {

    @Autowired

    TimeService  timeService;

    @RequestMapping("getTime")

    @ResponseBody

    public String  getTime(HttpServletRequest request){

           timeService.time();

           return "success";

    }

}

请求:http://localhost:8080/test/getTime ,后台输出打印信息:

service:1527081205419

=====123

service:1527081205419

以上测试发现Spring采用了JDK动态代理。

三、Spring选择用JDK动态代理还是CGLIB代理的依据:

   (1)当Bean实现接口时,Spring就会用JDK动态代理

   (2)当Bean没有实现接口时,Spring使用CGLIB代理

    (3)可以强制使用CGLIB(在Spring配置中使用:aop:aspectj-autoproxy proxy-target-class="true")

相关文章

网友评论

    本文标题:spring aop

    本文链接:https://www.haomeiwen.com/subject/kwedjftx.html