首页 > 编程语言 > 详细

Spring AOP通过注解的方式设置切面和切入点

时间:2019-06-30 16:44:41      阅读:82      评论:0      收藏:0      [点我收藏+]

切面相当于一个功能的某一个类,切入点是这个类的某部分和需要额外执行的其他代码块,这两者是多对多的关系,在代码块处指定执行的条件。

Aspect1.java

package com.yh.aop.schema.advice.myAspect;

public class Aspect1 {
    
    public void doIt() {
        System.out.println("Aspect1:do");
    }
}

 

PointCut1.java

package com.yh.myPointCut;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class PointCut1 {

    @Before("execution(* com.yh.aop.schema.advice.myAspect.Aspect1.*(..))")
    public void before() {
        System.out.println("PointCut1:before");
    }

}

 

applicationContext.xml

<?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:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">

     <context:component-scan base-package="com.yh"></context:component-scan>
     <context:component-scan base-package="com.yh.myPointCut"></context:component-scan>
 
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
    
    <bean id="aspect1" class="com.yh.aop.schema.advice.myAspect.Aspect1"></bean>
    
</beans>

 

MyTest.java

@Test
public void testPointCut(){
    String xmlPath="applicationContext.xml";
    ApplicationContext context = new ClassPathXmlApplicationContext(xmlPath);
    Aspect1 aspect1 = (Aspect1) context.getBean("aspect1");
    aspect1.doIt();
}

 

Spring AOP通过注解的方式设置切面和切入点

原文:https://www.cnblogs.com/YeHuan/p/11110208.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!