栏目分类:
子分类:
返回
文库吧用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
文库吧 > IT > 软件开发 > 后端开发 > Java

java之AOP动态代理

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java之AOP动态代理

一个例子:

package com.zg.spring.proxy;


public interface Calculator {
    int add(int i, int j);
    int sub(int i, int j);
    int mul(int i, int j);
    int div(int i, int j);
}

package com.zg.spring.proxy;


public class CalculatorImpl implements Calculator {
    @Override
    public int add(int i, int j) {
        System.out.println("日志,方法:add,参数:"+i+","+j);
        int result = i+j;
        System.out.println("计算结果为"+result);
        return result;
    }

    @Override
    public int sub(int i, int j) {
        System.out.println("日志,方法:sub,参数:"+i+","+j);
        int result = i-j;
        System.out.println("计算结果为"+result);
        return result;
    }

    @Override
    public int mul(int i, int j) {
        System.out.println("日志,方法:mul,参数:"+i+","+j);
        int result = i*j;
        System.out.println("计算结果为"+result);
        return result;
    }

    @Override
    public int div(int i, int j) {
        System.out.println("日志,方法:div,参数:"+i+","+j);
        int result = i/j;
        System.out.println("计算结果为"+result);
        return result;
    }
}

package com.zg.spring.proxy;

import java.lang.reflect.Array;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;


public class ProxyFactory {

    public ProxyFactory(Object target) {
        this.target = target;
    }

    private Object target;

    public Object getProxy(){
//        lassLoader loader, 指定加载动态生成的代理类的类加载器
//        Class[] interfaces, 获取目标对象实现的所有接口的class对象数组
//         InvocationHandler h)
        ClassLoader classLoader = this.getClass().getClassLoader();
        Class[] interfaces = target.getClass().getInterfaces();
        InvocationHandler h = new InvocationHandler() {
            @Override
            //proxy 代理对象,method要执行的方法,args 要执行的方法的参数列表
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("日志,方法: " +method.getName()+", 参数:"+ Arrays.toString(args));
                Object res = method.invoke(target, args);
                System.out.println("日志,方法: " +method.getName()+", 结果:"+ res);
                return res;

            }
        };

        return Proxy.newProxyInstance(classLoader,interfaces,h);
    }


}

package com.zg.test;

import com.zg.spring.proxy.Calculator;
import com.zg.spring.proxy.CalculatorImpl;
import com.zg.spring.proxy.ProxyFactory;
import org.junit.Test;


public class ProxyTest {

    @Test
    public void testProxy(){
        ProxyFactory proxyFactory = new ProxyFactory(new CalculatorImpl());
        Calculator proxy = (Calculator)proxyFactory.getProxy();
        proxy.add(1,2);
        proxy.mul(3,6);
    }
}



    4.0.0

    com.zg.sbootT1
    sbootT1
    1.0-SNAPSHOT

    pom

    
        
            org.springframework
            spring-context
            5.3.22
        
        
        
            junit
            junit
            4.12
            test
        

        
        
            org.mybatis
            mybatis
            3.5.6
        

        
            log4j
            log4j
            1.2.14
        

        
        
            mysql
            mysql-connector-java
            8.0.26
        

        
        
            com.alibaba
            druid
            1.0.31
        
    



使用基于注解的AOP:




    
    
    

    
    


package com.zg.spring.aop.annotation;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
@Aspect //切面
public class LoggerAspect {

//    @Before("execution(public int com.zg.spring.aop.annotation.CalculatorImpl.add(int,int))")
//    //@Before("execution(public int com.zg.spring.aop.annotation.CalculatorImpl.*(..))")
//    public void beforeAdviceMethod(){
//        System.out.println("LoggerAspect,前置通知");
//    }


    @Pointcut("execution(* com.zg.spring.aop.annotation.CalculatorImpl.*(..))")
    public void pointCut(){}

    public void beforeAdviceMethod(JoinPoint joinPoint){
        //获取连接点所对应方法的签名信息
        Signature signature = joinPoint.getSignature();
        //获取连接点所对应方法的参数
        Object[] args = joinPoint.getArgs();

        System.out.println("LoggerAspect,方法:"+signature.getName()+",参数:"+ Arrays.toString(args));

    }

    @After("pointCut()")
    public void afterAdviceMethod(JoinPoint joinPoint){
        //获取连接点所对应方法的签名信息
        Signature signature = joinPoint.getSignature();
        System.out.println("LoggerAspect,方法:"+signature.getName()+",执行完毕");
    }


    
    @AfterReturning(value = "pointCut()", returning = "result")
    public void afterReturningAdviceMethod(JoinPoint joinPoint, Object result){
        //获取连接点所对应方法的签名信息
        Signature signature = joinPoint.getSignature();
        System.out.println("LoggerAspect,方法:"+signature.getName()+",结果:"+result);
    }

    
    @AfterThrowing(value = "pointCut()", throwing = "ex")
    public void afterThrowingAdviceMethod(JoinPoint joinPoint, Throwable ex){
        //获取连接点所对应方法的签名信息
        Signature signature = joinPoint.getSignature();
        System.out.println("LoggerAspect,方法:"+signature.getName()+",异常:"+ex);
    }

    @Around("pointCut()")
    //环绕通知的方法的返回值一定要和目标对象方法的返回值一致
    public Object aroundAdviceMethod(ProceedingJoinPoint joinPoint){
        Object result = null;
        try {
            System.out.println("环绕通知-->前置通知");
            //表示目标对象方法的执行
            result = joinPoint.proceed();
            System.out.println("环绕通知-->返回通知");
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            System.out.println("环绕通知-->异常通知");
        } finally {
            System.out.println("环绕通知-->后置通知");
        }
        return result;
    }
}

package com.zg.spring.aop.annotation;

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

@Component
@Aspect
@Order(1)
public class ValidateAspect {
    //@Before("execution(* com.atguigu.spring.aop.annotation.CalculatorImpl.*(..))")
    @Before("com.zg.spring.aop.annotation.LoggerAspect.pointCut()")
    public void beforeMethod(){
        System.out.println("ValidateAspect-->前置通知");
    }
}

package com.zg.spring.test;

import com.zg.spring.aop.annotation.Calculator;
import com.zg.spring.aop.annotation.CalculatorImpl;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AOPTest {

    @Test
    public void testAOPByAnnotation(){
        ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("aop-annotation.xml");

        //使用了AOP 就不能直接访问,必须通过代理对象访问。
//        CalculatorImpl calculator = ioc.getBean(CalculatorImpl.class);
//        calculator.add(3,4);

        Calculator calculator = ioc.getBean(Calculator.class);
        calculator.add(3,4);
    }
}

ssm练习:

properties配置:

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/OneToMany?useUnicode=true&characterEncoding=utf8&autoReconnect=true&serverTimezone=UTC
jdbc.username=root
jdbc.password=123456

mybatis-config.xml





    
    

    
    
        
    

    
        
        
    

    
        
            
            
                
                
                
                

            
        
    

    
        
        
        
    

package com.zg.mybatis.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;


public class SqlSessionUtil {
    public static SqlSession getSqlSession(){
        SqlSession sqlSession =null;
        try {
            //获取核心配置文件输入流
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            //获取SqlSessionFactory对象
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
            SqlSessionFactory build = sqlSessionFactoryBuilder.build(is);
            //获取sql会话对象SqlSession
            sqlSession = build.openSession(true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sqlSession;
    }
}

package com.zg.mybatis.mapper;

import com.zg.mybatis.project.Aticle;
import org.apache.ibatis.annotations.MapKey;
import org.apache.ibatis.annotations.Param;

import java.util.List;
import java.util.Map;

public interface AticleMapper {

    //int insertAticle();


    Aticle getAticleById();

    Aticle getAticleByTitle(String Title);

    Aticle getAticleByTitleAndMsg(String Title, String Msg);

    Aticle getAticleByTitleAndMsgByMap(Map map);

    List getAllAticle();

    void insertAticle(Aticle aticle);

    //可以在mapper接口上使用@Param 注解,这样@Param("Title") 列名被标注为map的键
    void insertAticleByParam(@Param("Title") String t, @Param("Message") String msg);

    //通过param 定义键值对 @Param("Id") 为键,表名,String id 为传入值
    Aticle getAticleByIdParam(@Param("Id") String id);

    int getCount();

    //根据Id查询所有值,并返回键值对

    List> getAticleByIdToMap();

    //使用Map注解:"id"区分大小写
    @MapKey("id")
    Map getAticleByIdToMap2();
}








    

    
        
    

    
    
    
    
        select * from Aticle where id=1
    

    
    
        
    

    
    
        xxxx}-->
        
        select * from Aticle where Title = '${xxxx}'
    

    
    
        select * from Aticle where Title = #{Title} and Message = #{Message}
    

    
    
        insert into Aticle values(null, #{Title}, #{Message})
    

    
    
        insert into Aticle values(null, #{Title}, #{Message})
    

    
    
        select count(*) from Aticle
    

    
    
        select * from Aticle
    


package com.zg.mybatis.project;

public class Aticle {
    public Aticle() {
    }

    public Aticle(Integer id, String title, String message) {
        this.id = id;
        Title = title;
        Message = message;
    }

    private Integer id;
    private  String Title;
    private  String Message;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getTitle() {
        return Title;
    }

    public void setTitle(String title) {
        Title = title;
    }

    public String getMessage() {
        return Message;
    }

    public void setMessage(String message) {
        Message = message;
    }



    @Override
    public String toString() {
        return "Aticle{" +
                "id=" + id +
                ", Title='" + Title + ''' +
                ", Message='" + Message + ''' +
                '}';
    }
}

转载请注明:文章转载自 www.wk8.com.cn
本文地址:https://www.wk8.com.cn/it/1036760.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 wk8.com.cn

ICP备案号:晋ICP备2021003244-6号