spring动态代理的开发步骤如下:
1.创建原始对象(目标对象)
public class UserServiceImpl implements UserService1 {public void login(String name, String password) {System.out.println("login.method");}public void logout() {System.out.println("logout.method");}
}
2.额外功能
MethodBeforeAdvice接口
1.额外的功能书写在接口的实现类中,运行在原始方法执行之前运行额外功能。
import org.springframework.aop.MethodBeforeAdvice;import java.lang.reflect.Method;public class Before implements MethodBeforeAdvice {//作用:需要把运行在原始方法之前运行的额外功能代码,写在before方法中public void before(Method method, Object[] objects, Object o) throws Throwable {System.out.println("执行methodBeforeAdvice方法");}
}
3.定义切入点
1.切入点:额外功能加入的位置
2.目的:由程序员根据自己的需要,决定把额外功能添加给哪个原始方法
3.简单的测试:所有的方法都作为切入点,都加入额外的功能。
4.组装(第2,3步进行整合)
5.调用
1.目的:获得spring工厂创建的动态代理对象,并进行调用
2.spring的工厂通过原始对象的ID获取的是代理对象(在动态代理里,这是个硬性规定 。)
3.获得代理对象后,可以通过声明接口类型,进行对象的存储
编写代码
@Test
public void test13(){ApplicationContext ctx = new ClassPathXmlApplicationContext("/applicationContext4.xml");UserService1 userService = (UserService1) ctx.getBean("userService");userService.login("wang","123");userService.logout();
}
结果如下
Creating shared instance of singleton bean 'before'
执行methodBeforeAdvice方法
login.method
执行methodBeforeAdvice方法
logout.method
以上就是动态代理的创建过程,供参考
下一篇:uos 做deb包