spring半自动代理
1、被代理类接口Person.java
1 package com.xiaostudy; 2 3 /** 4 * @desc 被代理类接口 5 * 6 * @author xiaostudy 7 * 8 */ 9 public interface Person { 10 11 public void add(); 12 public void update(); 13 public void delete(); 14 }
2、被代理类PersonImple.java
1 package com.xiaostudy; 2 3 /** 4 * @desc 被代理类 5 * 6 * @author xiaostudy 7 * 8 */ 9 public class PersonImple implements Person { 10 11 /** 12 * @desc 实现接口方法 13 */ 14 public void add() { 15 System.out.println("add()>>>>>>>>"); 16 } 17 18 @Override 19 public void update() { 20 System.out.println("update()>>>>>>>>"); 21 } 22 23 @Override 24 public void delete() { 25 System.out.println("delete()>>>>>>>>"); 26 } 27 28 }
3、切面类MyAdvice.java
1 package com.xiaostudy; 2 3 import org.aopalliance.intercept.MethodInterceptor; 4 import org.aopalliance.intercept.MethodInvocation; 5 6 /** 7 * @desc 切面类 8 * 9 * @author xiaostudy 10 * 11 */ 12 public class MyAdvice implements MethodInterceptor { 13 14 /** 15 * @desc 环绕通知 16 */ 17 @Override 18 public Object invoke(MethodInvocation method) throws Throwable { 19 System.out.println("日记开始>>>>>>>>>>>"); 20 method.proceed(); 21 System.out.println("日记结束<<<<<<<<<<<<"); 22 return null; 23 } 24 25 }
4、spring配置文件applicationContext.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans 5 http://www.springframework.org/schema/beans/spring-beans.xsd"> 6 <!-- 创建被代理类 --> 7 <bean id="person" class="com.xiaostudy.PersonImple"></bean> 8 <!-- 创建切面类 --> 9 <bean id="advice" class="com.xiaostudy.MyAdvice"></bean> 10 <!-- 创建代理类 --> 11 <bean id="proxyPerson" class="org.springframework.aop.framework.ProxyFactoryBean"> 12 <!-- 把被代理类接口引入进来 --> 13 <property name="interfaces" value="com.xiaostudy.Person"></property> 14 <!-- 把被代理类引入进来 --> 15 <property name="target" ref="person"></property> 16 <!-- 把切面类引入进来,是以字符串形式引入,所以是用value,而不是用ref --> 17 <property name="interceptorNames" value="advice"></property> 18 <!-- 非必须项:value为true表示强制使用cglib代理 --> 19 <property name="optimize" value="true"></property> 20 </bean> 21 </beans>
5、测试类Test.java
1 package com.xiaostudy; 2 3 import org.springframework.context.ApplicationContext; 4 import org.springframework.context.support.ClassPathXmlApplicationContext; 5 6 /** 7 * @desc 测试类 8 * 9 * @author xiaostudy 10 * 11 */ 12 public class Test { 13 14 public static void main(String[] args) { 15 ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); 16 Person person = ac.getBean("proxyPerson", Person.class); 17 person.add(); 18 person.update(); 19 person.delete(); 20 } 21 22 }