使用AspectJ来产生动态代理

AOP的实现者:

     AspectJ ,  AspectWerkz,  JBoss AOP,  Spring AOP.

     在Spring2.0中,Spring AOP , IoC和AspectJ整合到一起了。

要理解AOP就必须要先知道动态代理,Spring AOP底层使用了两种代理机制:一种是基于JDK的动态代理;一种是基于CGLib的动态代理。之所以要有两种代理机制,很大程度上是因为JDK本身只提供接口的代理,而不支持类的代理。

看api理解那几个专业名词

下面就是一个AspectJ产生代理的一个例子

先要让程序支持AspectJ,看bean.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"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
	<context:annotation-config />
	<context:component-scan base-package="com.lbx"/>
 	<aop:aspectj-autoproxy />
 	
</beans>

需要在目标类中方法执行前加入的处理(相当于拦截器)@AspectJ

注意:一定要加@Componnent

package com.lbx.aop;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LogInterceptor {
	
	@Before("execution(public void com.lbx.dao.impl.UserDaoImpl.add(com.lbx.po.User))")
	public void before(){
		System.out.println("LogInterceptor.before()");;
	}
	
}

其他的类

package com.lbx.service.impl;


import javax.annotation.Resource;

import org.springframework.stereotype.Component;


import com.lbx.dao.UserDao;
import com.lbx.po.User;
import com.lbx.service.UserService;

@Component("userService")
public class UserServiceImpl implements UserService {
	private UserDao userDao;
	
	public void add(User user) {
		userDao.add(user);
	}
	
	public UserDao getUserDao() {
		return userDao;
	}
	@Resource(name="userDao")   //最好用@Resource 不要用@Autowired
	public void setUserDao( UserDao userDao) { 
		this.userDao = userDao;
	}
}
package com.lbx.dao.impl;

import org.springframework.stereotype.Component;

import com.lbx.dao.UserDao;
import com.lbx.po.User;

@Component("userDao")   //UserDaoImpl
public class UserDaoImpl implements UserDao {

	public void add(User user) {
		// TODO Auto-generated method stub
		System.out.println("一个user添加进来");
	}

}

  

相关推荐