beanAop03.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">
<bean id="us" class="com.qianfeng.aop03.UserServiceImpl"></bean>
<bean id="ma" class="com.qianfeng.aop03.MyAspect"></bean>
<!--
ProxyFactoryBean代理的FactoryBean对象,我们现在要代理的是us
包含四个属性注入:
1. interfaces: 接口对象们
<list>
<value>com.qfedu.aop03.IUserService</value>
<value>com.qfedu.aop03.IUserService</value>
<value>com.qfedu.aop03.IUserService</value>
</list>
2. target:目标对象,哪个对象将被以代理的方式创建
3. interceptorNames:拦截对象的名称,自定义的MethodInterceptor对象,注意它的包结构组成
4. optimize:boolean类型的值:
true:强制使用cglib的动态代理方式
false:使用jdk自带的动态代理
cglib:code generation library,代码生成库,性能更高
-->
<bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="interfaces" value="com.qianfeng.aop03.UserService"></property>
<property name="target" ref="us"></property>
<property name="interceptorNames" value="ma"></property>
<property name="optimize" value="true"></property>
</bean>
</beans>
UserService.java
package com.qianfeng.aop03;
import java.util.List;
public interface UserService {
List getUserList();
boolean delete(int uid);
boolean update(Object user);
boolean saveUser(Object user);
}
UserServiceImpl.java
package com.qianfeng.aop03;
import com.qianfeng.aop03.UserService;
import java.util.List;
public class UserServiceImpl implements UserService {
@Override
public List getUserList() {
System.out.println("查找用户");
return null;
}
@Override
public boolean delete(int uid) {
System.out.println("删除用户");
return false;
}
@Override
public boolean update(Object user) {
System.out.println("修改用户");
return false;
}
@Override
public boolean saveUser(Object user) {
System.out.println("更新用户");
return false;
}
}
MyAspect.java
package com.qianfeng.aop03;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class MyAspect implements MethodInterceptor {
public void Before(){
System.out.println("---Before---");
}
public void After(){
System.out.println("---After---"+'\n'+'\n');
}
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
Before();
Object proceed = methodInvocation.proceed();
After();
return proceed;
}
}
Aop03Text.java
package com.qianfeng.aop03;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Aop03Text {
@Test
public void text(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beanAop03.xml");
UserServiceImpl userService = context.getBean("proxy", UserServiceImpl.class);
userService.delete(1);
userService.getUserList();
userService.saveUser("");
userService.update("");
}
}