您的位置:首页 > 编程语言 > Java开发

spring学习----aop配置demo

2017-08-11 10:34 369 查看

注意

aop:aspect   切面类是普通类即可
aop:advisor  切面类必须实现  advice接口   如:MethodBeforeAdvice    AfterReturningAdvice等


定义通知(实现Advice)

public class MyAfterAdvice implements AfterReturningAdvice {
@Override
public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
System.out.println("=========我是afterReturn通知方法=============");
}
}


public class MyBeforeAdvice implements MethodBeforeAdvice{
@Override
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println("=========我是前置通知方法=============");
}
}


普通通知(不实现Advice)

public class MyNoAdvice {
public void before() throws Throwable {
System.out.println("=============我的普通的before前置方法====================");
}

public void after() throws Throwable {
System.out.println("=============我的普通的After后置方法====================");
}
}


业务类

public interface IBussinessService {
void bussiness();

void sayHello();
}


public class BussinessServiceImpl implements IBussinessService{
@Override
public void bussiness() {
System.out.println("=========我是业务方法==========");
}

@Override
public void sayHello() {
System.out.println("=========我是say Hello==========");
}
}


测试类

@Test
public void test1(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:beans.xml");
IBussinessService bussinessService =  applicationContext.getBean("bussinessService",IBussinessService.class);
bussinessService.bussiness();
}


配置文件

<!-- ==========================测试AOP============================= -->
<bean id="myBeforeAdvice" class="com.chenfei.advice.MyBeforeAdvice"></bean>
<bean id="myAfterAdvice" class="com.chenfei.advice.MyAfterAdvice"></bean>
<bean id="myNoAdvice" class="com.chenfei.advice.MyNoAdvice"/>
<bean id="bussinessService" class="com.chenfei.service.impl.BussinessServiceImpl"></bean>

<aop:config>
<aop:pointcut id="pointtest1" expression="execution(* com.chenfei.service.impl.*.*(..))" />
<aop:aspect ref="myNoAdvice">
<aop:before method="before" pointcut-ref="pointtest1"/>
<aop:after method="after" pointcut-ref="pointtest1"/>
</aop:aspect>
</aop:config>
<aop:config>
<aop:pointcut id="pointtest2" expression="execution(* com.chenfei.service.impl.*.*(..))" />
<aop:advisor pointcut-ref="pointtest2" advice-ref="myBeforeAdvice" />
<aop:advisor pointcut-ref="pointtest2" advice-ref="myAfterAdvice" />
</aop:config>


测试结果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: