05 配置方式完成aop

前面几节我们使用三种方式完成了代理,接下来,我们将看一下在spring中如何完成aop。

1、前提约束

2、操作步骤

  • 在src/main/resources文件夹下创建application-config-aop.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="userService" class="net.wanho.service.UserService"></bean>

    <bean id="youraspect" class="net.wanho.aspect.YourAspect"></bean>
    <aop:config>
        <aop:pointcut id="pt" expression="execution(* net.wanho.service.*.*(..))"/>
        <aop:aspect id="aspect" ref="youraspect">
            <aop:after method="after"  pointcut-ref="pt"></aop:after>
            <aop:before method="before" pointcut-ref="pt"></aop:before>
        </aop:aspect>
    </aop:config>
</beans>
  • 在src/main/java文件夹下创建net.wanho.service.UserService.java,内容如下:
public class UserService {
    public void query() {
        System.out.println("query");
    }
}
  • 在src/main/java文件夹下创建net.wanho.aspect.YourAspect.java,内容如下:
public class YourAspect{
    public void before()
    {
        System.out.println("before");
    }
    public void after()
    {
        System.out.println("after");
    }
}
  • 在src/main/java文件夹下创建Test.java,内容如下:
public class Test{
        public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("application-config-aop.xml");
        UserService userService = applicationContext.getBean("userService",UserService.class);
        userService.query();
    }
}

以上就是通过配置方式完成aop的过程。

posted @ 2020-03-23 20:10  张力的程序园  阅读(114)  评论(0)    收藏  举报