java AOP使用配置项来进行注入实践

场景:

在目标方法前面和后面执行通知方法

 

目标类

@Component
public class Play {

    public void watchTV(){
        System.out.println("目标执行方法,正在看电视");
    }
}

切面类

public class WatchTVAspect {

    public void beforeAdvice(){
        System.out.println("切点函数执行前的方法");
    }

    public void afterAdvice(){
        System.out.println("切点函数执行后的方法");
    }

    public void afterReturning(){
        System.out.println("目标方法返回时执行 ,后置返回通知");
    }

    public void afterThrowing(){
        System.out.println("目标方法抛出异常时执行 异常通知");
    }

    public void around(){
        System.out.println("在目标函数执行中执行,可控制目标函数是否执行,环绕通知");
    }
}

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

    <context:component-scan base-package="com.mb"></context:component-scan>

    <bean id="watchTv" class="com.mb.util.WatchTVAspect"></bean>
    <aop:config>
        <aop:aspect id="check" ref="watchTv">
            <aop:pointcut id="accountPoint" expression="execution(* com.mb.common.Play.*(..))"></aop:pointcut>
            <aop:before  pointcut-ref="accountPoint" method="beforeAdvice"></aop:before>
            <aop:after  pointcut-ref="accountPoint" method="afterAdvice"></aop:after>
            <!--<aop:around method="around" pointcut-ref="accountPoint" ></aop:around>-->
            <!--<aop:after-returning method="afterReturning" pointcut-ref="accountPoint"></aop:after-returning>-->
            <!--<aop:after-throwing method="afterThrowing" pointcut-ref="accountPoint"></aop:after-throwing>-->
        </aop:aspect>
    </aop:config>
</beans>

测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:**/applicationContext*.xml"})
public class DemoTest {

    @Autowired
    Play play;

    @Test
    public void aspectTest(){
        play.watchTV();

    }
}

测试结果:
切点函数执行前的方法
目标执行方法,正在看电视
切点函数执行后的方法

 

posted @ 2019-01-24 18:10  就这个名字好  阅读(443)  评论(0编辑  收藏  举报