Spring中的AOP

AOP(Aspect Oriented Program)面向切面编程

1.构建两个类

@Component("book")
public class Book {
    public void lala(){
        System.out.println("lalala.......");
    }
}
@Component("mybook")
@Aspect
public class MyBook {
    String name;
    @Before(value="execution(* Pojo.Book.*(..))")
    public void before1(){
        System.out.println("前置。。。");
    }

    @After(value="execution(* Pojo.Book.*(..))")
    public void after1(){
        System.out.println("后置。。。");
    }

    @Around(value="execution(* Pojo.Book.*(..))")
    public void around(ProceedingJoinPoint proceedingJoinPoint)throws Throwable{
        System.out.println("方法之前。。。"+proceedingJoinPoint.getSignature().getName());
        proceedingJoinPoint.proceed();
        System.out.println("方法之后。。。"+proceedingJoinPoint.getSignature().getName());
    }
}

在mybook类中,先用@Aspect声明该类是一个切面。再用@Before,@After,@Around三种方法分别进行AOP操作,execution中是定位到具体切点的方法上面。

2.AOPBean.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:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:annotation-config/>                <!--开启自动注入注解@autowired-->

    <context:component-scan base-package="Pojo"/>   <!--Bean注解扫描开启-->

    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>    <!--开启AOP扫描-->

</beans>

(1)开启自动注入扫描

(2)开启Bean注解扫描

(3)开启AOP扫描

3.在Test中直接调用切点所在方法

public class AOPTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("AOPBean.xml");
        Book book = (Book)context.getBean("book");
        book.lala();
    }
}

得到结果



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值