(1)jar包
(2)目录结构
(3)PersonService.java类
package com.huawei.aop.factory;
public interface PersonService {
public void addPerson();
public void updatePerson();
}
(4)(3)PersonServiceImpl.java类
package com.huawei.aop.factory;
public class PersonServiceImpl implements PersonService {
@Override
public void addPerson() {
System.out.println("factory addperson");
}
@Override
public void updatePerson() {
System.out.println("bfactory addperson");
}
}
(5)MyAspect.java类
package com.huawei.aop.factory;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class MyAspect implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
System.out.println("before");
//执行目标方法
Object obj = mi.proceed();
System.out.println("after");
return obj;
}
}
(6)配置文件beans.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 1目标类 -->
<bean id="personServiceId" class="com.huawei.aop.factory.PersonServiceImpl"></bean>
<!-- 2切面类,含有通知 -->
<bean id="myAspect" class="com.huawei.aop.factory.MyAspect"></bean>
<!-- 3代理类
* ProxyFactoryBean 用于生产代理类一个特殊的工厂bean
proxyInterfaces 用于确定需要实现接口
interceptorNames 用于确定通知实现类,需要提供的bean名称
target 用于确定代理类bean名称
-->
<bean id="personServiceProxyId" class="org.springframework.aop.framework.ProxyFactoryBean">
<!-- 3.1 确定接口 -->
<property name="proxyInterfaces" value="com.huawei.aop.factory.PersonService"></property>
<!-- 3.2 确定通知 -->
<property name="interceptorNames" value="myAspect"></property>
<!-- 3.3 确定目标类-->
<property name="target" ref="personServiceId"></property>
<!-- 3.4 设置true,强制使用 cglib -->
<property name="optimize" value="true"></property>
</bean>
</beans>
(7)单元测试类TestApp.java
package com.huawei.aop.factory;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestApp {
@Test
public void demo01(){
//获得目标类
String xmlPath = "/com/huawei/aop/factory/beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
PersonService personService = applicationContext.getBean("personServiceId",PersonService.class);
personService.addPerson();
personService.updatePerson();
}
@Test
public void demo02(){
//获得代理类
String xmlPath = "/com/huawei/aop/factory/beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
PersonService personService = applicationContext.getBean("personServiceProxyId",PersonService.class);
personService.addPerson();
personService.updatePerson();
}
}