spring默认使用jdk代理
jdk代理:只能代理实现了接口的类
CGLIB代理:不仅可以对实现接口的类进行代理,同时也可以对类本身生成代理(主要是通过继承这个类来生成的,所以不要将要代理的类设成final)
以下演示CGLIB对类的代理
[java] view plaincopy
1. //要生成代理的类
2. public class UserManagerImpl {
3. //implements UserManager {
4.
5. public void addUser(String username, String password) {
6. //checkSecurity();
7. System.out.println("---------UserManagerImpl.add()--------");
8. }
9. }
10. //aspect类
11.
12. public class SecurityHandler {
13.
14. private void checkSecurity(JoinPoint joinPoint) {
15. for (int i=0; i<joinPoint.getArgs().length; i++) {
16. System.out.println(joinPoint.getArgs()[i]);
17. }
18.
19. System.out.println(joinPoint.getSignature().getName());
20.
21. System.out.println("-------checkSecurity-------");
22. }
23. }
配置文件
[xhtml] view plaincopy
1. <!-- 强制使用CGLIB代理 -->
2. <!--
3. <aop:aspectj-autoproxy proxy-target-class="true"/>
4. -->
5.
6. <bean id="userManager" class="com.bjpowernode.spring.UserManagerImpl"/>
7. <bean id="securityHandler" class="com.bjpowernode.spring.SecurityHandler"/>
8.
9. <aop:config>
10. <aop:aspect id="securityAspect" ref="securityHandler">
11. <!--
12. 以add开头的方法
13. <aop:pointcut id="addAddMethod" expression="execution(* add*(..))"/>
14. -->
15. <!--
16. com.bjpowernode.spring包下所有的类所有的方法
17. <aop:pointcut id="addAddMethod" expression="execution(* com.bjpowernode.spring.*.*(..))"/>
18. -->
19. <aop:pointcut id="addAddMethod" expression="execution(* com.bjpowernode.spring.*.add*(..)) || execution(* com.bjpowernode.spring.*.del*(..))"/>
20. <aop:before method="checkSecurity" pointcut-ref="addAddMethod"/>
21. </aop:aspect>
22. </aop:config>
client
[java] view plaincopy
1. BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");
2. //UserManager userManager = (UserManager)factory.getBean("userManager");
3. UserManagerImpl userManager = (UserManagerImpl)factory.getBean("userManager");