第二讲 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>
原文地址:https://www.cnblogs.com/lljj/p/spring02.html