zoukankan      html  css  js  c++  java
  • 第二讲 SpringAop

    IOC——控制反转。

    DI —— 依赖注入

    AOP—— 面向切面编程。

     

     

    实现AOP的技术:设计模式(代理模式——静态代理、动态代理(JDK代理)、适配器模式、单例模式、工厂模式)、使用Spring中代理模式(CGLIB代理(没有用接口,直接写类)、JDK动态代理(使用了接口))。

     

    静态代理(功能强悍程度:★☆☆☆☆)

     

    public class UserInfoDAOProxy implements IUserInfoDAO {
    
        private IUserInfoDAO iuser;
        
        private Log log = new Log();
        
        public UserInfoDAOProxy(IUserInfoDAO iuser){
            this.iuser = iuser;        
        }
    
        public void addUser() {
            log.begin();
            
            iuser.addUser();
            
            log.end();
        }
    }

     

    动态代理(功能强悍程度:★★☆☆☆)

    利用Java反射技术,来实现代理所有接口。

     

     

    public class DyProxy implements InvocationHandler{
        
        private Object obj;
        
        public DyProxy(Object obj){
            this.obj = obj;
        }
        
        /**
         * 用来获取代理之后的Object对象
         */
        public Object getObject(){
            
            //将obj对象,转化一下
            return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(),this);
        }
        
        //invoke 执行指定的方法
        public Object invoke(Object proxy, Method method, Object[] args)
                throws Throwable {
            
            Log log = new Log();
            
            log.begin();
            
            //调用目标方法
            Object result = method.invoke(obj, args);
            
            log.end();
            
            return result;
        }    
    }

     

     

    总结:需要在目标方法前或后执行相关操作,必须使用代理器。

     

     

     

    Spring中代理(功能强悍程度:★★★★★★★★★★)

    <!-- 通知对象(增强) -->
        <bean id="logobj" class="com.zuxia.util.Log" />
        
        <!-- 目标对象(target) -->
        <bean id="udao" class="com.zuxia.dao.UserInfoDAO" />
     
        <!-- 配置aop的切面操作 -->
        <aop:config>
            <!-- 切入点 -->
            <aop:pointcut expression="execution(* com.zuxia.dao.*.add*(..))" id="firstPointCut"/>
            
            <!-- 配置切面 -->
            <aop:aspect id="test" ref="logobj">
                <aop:before method="begin" pointcut-ref="firstPointCut"/>
                <aop:after method="end" pointcut-ref="firstPointCut"/>
            </aop:aspect>
            
        </aop:config>
  • 相关阅读:
    mybatis05--多条件的查询
    mybatis04--Mapper动态代理实现
    mybatis03--字段名和属性名不一致
    mybatis02--增删改查
    myBatis01
    hibernate12--缓存
    hibernate11--Criteria查询
    hibernate10--命名查询
    hibernate09--连接查询
    (转载)閱讀他人的程式碼(5)找到程式入口,再由上而下抽絲剝繭
  • 原文地址:https://www.cnblogs.com/lljj/p/spring02.html
Copyright © 2011-2022 走看看