spring实现AOP
一、.默认advisor自动代理生成器(实现前置增强)
1.编写接口类
public interface ISomeService {
public void doSome();
public void add();
}
2.实现接口类中的方法
public class SomeService implements ISomeService {
public void doSome() {
System.out.println("code ok");
}
public void add() {
System.out.println("=========log===============");
}
}
3.编写增强类
public class MyBeforeAdvice implements MethodBeforeAdvice {
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println("执行前置增强");
}
}
4.写配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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="SomeService" class="cn.happy.service.SomeService"></bean>
<!--增强 通知-->
<bean id="beforeAdvice" class="cn.happy.service.MyBeforeAdvice"></bean><!--前置增强-->
<!-- 使用名称匹配方法切入点顾问NameMatchMethodPointcutAdvisor-->
<bean id="beforeAdvisor" class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">
<!-- <!–顾问 Advisor 包装通知, 那个方法需要增强–>-->
<property name="advice" ref="beforeAdvice"></property>
<property name="mappedNames" value="doSome"></property>
</bean>
<!--默认advisor自动代理生成器 有几个目标方法都会增强,但是只能对顾问自动代理,不能自动代理通知-->
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"></bean>
</beans>
5.测试方法
public class test01 {
// AspectJ
@Test
public void testAspect(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
ISomeService someService= (ISomeService)context.getBean("SomeService");
someService.add();
someService.doSome();
}
6.测试结果


浙公网安备 33010602011771号