Spring AOP开发简单实例(不带切点的切面)

来源:互联网 发布:win7网络打印被挂起 编辑:程序博客网 时间:2024/05/21 09:54

1. 导入相应的jar包
 <1>spring-aop-3.2.0.RELEASE.jar
 <2>Spring依赖包中的com.springsource.org.aopalliance-1.0.0.jar

2. 编写被代理对象
<1>接口CustomerDao:

public interface CustomerDao {    public void add();    public void update();    public void delete();    public void find();}

<2>CustomerDao的实现类CustomerDaoImpl:

public class CustomerDaoImpl implements CustomerDao {    public void add() {        System.out.println("添加客户!!");    }    public void update() {        System.out.println("修改客户!!");    }    public void delete() {        System.out.println("删除客户!!");    }    public void find() {        System.out.println("查找客户!!");    }}

3. 编写增强代码
 编写增强代码,这边选择前置增强:

public class MyBeforeAdvice implements MethodBeforeAdvice{    public void before(Method method, Object[] args, Object target)            throws Throwable {        /**         * method:执行的方法。         * args:参数。         * target:目标对象。         */        System.out.println("============前置增强===============");    }}

4. 配置信息并配置生成代理
* 属性:
target : 代理的目标对象
proxyInterfaces : 代理要实现的接口
如果多个接口可以使用以下格式赋值

<list>    <value></value>    ....</list>

proxyTargetClass : 是否对类代理而不是接口,设置为true时,使用CGLib代理
interceptorNames : 需要织入目标的Advice
singleton : 返回代理是否为单实例,默认为单例
optimize : 当设置为true时,强制使用CGLib

 信息配置

<!-- 被增强对象 -->    <bean id="customerDao" class="com.demo.CustomerDaoImpl"></bean>    <!-- 定义增强 -->    <bean id="beforeAdvice" class="com.demo.MyBeforeAdvice"></bean>

 生成代理的Spring基于ProxyFactoryBean类,底层自动选择使用JDK动态代理还是CGLib的代理。

<!-- Spring支持配置生成代理 -->    <bean id="customerDaoProxy" class="org.springframework.aop.framework.ProxyFactoryBean">        <!-- 设置目标对象 -->        <property name="target" ref="customerDao"></property>        <!-- 设置实现的接口,value中写接口的全路径 -->        <property name="proxyInterfaces" value="cn.itcast.demo1.CustomerDao"></property>        <!-- 需要使用value:要的是名称 -->        <property name="interceptorNames" value="beforeAdvice"></property>    </bean>
  1. 测试使用
@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:applicationContext.xml")public class SpringTest3 {    @Autowired    @Qualifier("customerDaoProxy")      private CustomerDao customerDao;    @Test    public void demo1(){        customerDao.add();        customerDao.update();        customerDao.delete();        customerDao.find();    }}

6. 测试结果

============前置增强===============添加客户!!============前置增强===============修改客户!!============前置增强===============删除客户!!============前置增强===============查找客户!!