AOP实现方式2——通过AspectJ提供的注解实现AOP

1.Runable接口

 
 
package com.animal;

/**
 * Created by kenneth on 2017/4/6.
 */
public interface Runable {
    void run();
}

2.Runable接口的实现类Dog

package com.animal;

/**
 * Created by kenneth on 2017/4/6.
 */
public class Dog implements Runable {
    @Override
    public void run() {
        System.out.println("小狗在跑");
    }
}

3.Spring注解对bean的方法进行拦截器

package com.animal;

import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

/**
 * Created by kenneth on 2017/4/6.
 */
@Aspect
public class RunHelper {

    @Pointcut("execution(* com.animal.Dog.*(..))")
    public void runMethod() {
    }

    @Before("runMethod()")
    public void beforeRun() {
        System.out.println("跑前要热身");
    }

    @AfterReturning("runMethod()")
    public void afterRun() {
        System.out.println("跑完要喝水");
    }
}

4.Spring配置文件

<?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">

    <!--启用AspectAnnotation的支持-->
    <aop:aspectj-autoproxy/>
    <bean id="dog" class="com.animal.Dog"/>
    <bean id="runHelper" class="com.animal.RunHelper"/>

</beans>

5.测试类

package com.animal;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Created by kenneth on 2017/4/6.
 */
public class Test {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
        Runable dog = (Runable) context.getBean("dog");
        dog.run();
    }
}

6.测试结果:

四月 06, 2017 1:33:21 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@533ddba: startup date [Thu Apr 06 13:33:21 CST 2017]; root of context hierarchy
四月 06, 2017 1:33:21 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [ApplicationContext.xml]
跑前要热身
小狗在跑
跑完要喝水

发布了14 篇原创文章 · 获赞 8 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/langwuzhe/article/details/78808750