码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式(六) xml方式实现AOP

时间:2017-02-19 19:55:49      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:运行   pre   new   auto   for   oca   ica   image   技术   

1.1、

    Aop  aspect object programming  面向切面编程

                    功能: 让关注点代码与业务代码分离!

            关注点,

                  重复代码就叫做关注点;

            切面,

                   关注点形成的类,就叫切面()

                   面向切面编程,就是指 对很多功能都有的重复的代码抽取,再在运行的时候往业务方法上动态植入“切面类代码”。

            切入点,

                  执行目标对象方法,动态植入切面代码。

                  可以通过切入点表达式,指定拦截哪些类的哪些方法; 给指定的类在运行的时候植入切面类代码。

代码示例如下:

 

UserDao  目标对象

 

package com.murong.aop;


/**
 * 目标对象
 */
public class UserDao
{
    public void save()
    {
        System.out.println("-----核心业务:保存!!!------");
    }
}

 

Aop  切面类

package com.murong.aop;

/**
 *切面类
 */
public class Aop
{
    public  void testPointCut(){

    }
    public void begin()
    {
        System.out.println("事务开启");
    }//关注点代码

    public void end()
    {
        System.out.println("事务结束");
    }//关注点代码
}

ApplicationContext  配置文件

<?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:p="http://www.springframework.org/schema/p"
       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.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd"
       default-autowire="byType">

    <bean id="userDao" class="com.murong.aop.UserDao"/>
    
    <bean id="aop" class="com.murong.aop.Aop"/>
    
    <aop:config>
        <aop:aspect ref="aop">
                <aop:before method="begin" pointcut="execution(* com.murong.aop.UserDao.*(..))"></aop:before>
                <aop:after method="end" pointcut="execution(* com.murong.aop.UserDao.*(..))"></aop:after>
        </aop:aspect>
    </aop:config>


</beans>

App  测试类

package com.murong.aop;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App
{
    private ApplicationContext ac = new ClassPathXmlApplicationContext("com/murong/aop/applicationContext");
    @Test
    public void test()
    {
        UserDao dao = (UserDao) ac.getBean("userDao");
        dao.save();
    }
}

结果:

技术分享

 

设计模式(六) xml方式实现AOP

标签:运行   pre   new   auto   for   oca   ica   image   技术   

原文地址:http://www.cnblogs.com/yuanchaoyong/p/6416541.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!