博客
关于我
Spring (AOP、静态代理、动态代理)
阅读量:258 次
发布时间:2019-03-01

本文共 2872 字,大约阅读时间需要 9 分钟。

Spring AOP技术指南

1. AOP简介

AOP(Aspect Oriented Programming,面向切面编程)是一种软件开发方法,旨在提高开发效率和代码复用性。传统的编程模式通常需要重复编写相同功能的代码,例如性能监视、事务管理、安全检查和缓存处理。AOP通过引入切面(Aspect)来横向抽取这些功能,减少代码冗余。

1.1 AOP的核心概念

  • 切点(Joinpoint):指在委托类中可以被增强的方法。
  • 切入点(Pointcut):指定需要增强的方法。
  • 通知(Advice):增强的代码逻辑。
  • 目标对象(Target):委托类。
  • 织入(Weaving):将增强逻辑应用到目标类。
  • 代理(Proxy):增强后的类的代理类。
  • 切面(Aspect):切点和通知的结合。

1.2 Spring中的AOP实现

Spring提供了强大的AOP支持,主要通过动态代理实现。具体来说:

  • 基于AspectJ的AOP:Spring2.0及以上版本支持AspectJ切点表达式,允许直接在Bean类中定义切面。
  • @AspectJ注解:AspectJ1.5新增的注解技术,通过JDK5注解技术实现切面定义。

1.3 AspectJ切点表达式

AspectJ的切点表达式简洁且灵活,常见表达式包括:

execution(* com.example.service.MyService.myMethod(..))
  • execution:匹配方法调用。
  • *:表示任意访问修饰符(public、protected、private)。
  • com.example.service.MyService:指定包名。
  • myMethod(..):匹配方法名称及参数。

1.4 AOP的增强类型

在Spring中,常见的通知类型包括:

  • @Before:前置通知。
  • @AfterReturning:后置通知,可获取返回值。
  • @Around:环绕通知,可控制方法执行。
  • @AfterThrowing:异常通知。
  • @After:最终通知。

1.5 AOP编程案例

1.5.1 定义切面

@Aspect@Componentpublic class MyAspect {    @Before("execution(* com.example.dao.UserDao.addUser())")    public void beforeAdvice() {        System.out.println("用户添加前置通知");    }}

1.5.2 测试

@RunWith(SpringRunner.class)@ContextConfiguration("classpath:application-context.xml")public class TestUserDao {    @Autowired    private UserDao userDao;    @Test    public void testAdd() {        userDao.addUser();    }}

2. 代理模式

代理模式通过创建代理对象来间接操作目标对象,核心特点是:

  • 不直接操作目标对象。
  • 代理对象与目标对象实现同一接口。

2.1 静态代理

静态代理要求代理类和目标类实现同一接口,代码示例:

public interface WindWomen {    String say();}public class Pan implements WindWomen {    public String say() {        return "晚上十点小河边见......";    }}public class Wang implements WindWomen {    private WindWomen windWomen;    public Wang(WindWomen windWomen) {        this.windWomen = windWomen;    }    public String say() {        System.out.println("她找我让我给你带个话:");        System.out.println(windWomen.say());        System.out.println("记得啊!");        return null;    }}

2.2 动态代理

基于JDK的动态代理适用于接口实现,代码示例:

public class AgentTest {    public static void main(String[] args) {        final Pan pan = new Pan();        WindWomen windWomen = (WindWomen) Proxy.newProxyInstance(            AgentTest.class.getClassLoader(),            Pan.class.getInterfaces(),            new InvocationHandler() {                public Object invoke(Object proxy, Method method, Object[] args)                    throws Throwable {                    System.out.println("她找我让我给你带个话:");                    Object object = method.invoke(pan, args);                    System.out.println("记得啊!");                    return object;                }            }        );        windWomen.say();    }}

2.3 CGLIB动态代理

CGLIB动态代理基于继承,适用于类继承:

public class Wang2 extends Pan {    public String say() {        System.out.println("她找我让我给你带个话:");        System.out.println(super.say());        System.out.println("记得啊!");        return null;    }}

总结

通过以上内容,可以清晰地了解Spring AOP的核心概念、实现方式及其实际应用。无论是静态代理还是动态代理,都能有效提升代码复用性和维护性。

转载地址:http://isft.baihongyu.com/

你可能感兴趣的文章
npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
查看>>
npm install 报错 Failed to connect to github.com port 443 的解决方法
查看>>
npm install 报错 fatal: unable to connect to github.com 的解决方法
查看>>
npm install 报错 no such file or directory 的解决方法
查看>>
npm install 权限问题
查看>>
npm install报错,证书验证失败unable to get local issuer certificate
查看>>
npm install无法生成node_modules的解决方法
查看>>
npm install的--save和--save-dev使用说明
查看>>
npm node pm2相关问题
查看>>
npm run build 失败Compiler server unexpectedly exited with code: null and signal: SIGBUS
查看>>
npm run build报Cannot find module错误的解决方法
查看>>
npm run build部署到云服务器中的Nginx(图文配置)
查看>>
npm run dev 和npm dev、npm run start和npm start、npm run serve和npm serve等的区别
查看>>
npm run dev 报错PS ‘vite‘ 不是内部或外部命令,也不是可运行的程序或批处理文件。
查看>>
npm scripts 使用指南
查看>>
npm should be run outside of the node repl, in your normal shell
查看>>
npm start运行了什么
查看>>
npm WARN deprecated core-js@2.6.12 core-js@<3.3 is no longer maintained and not recommended for usa
查看>>
npm 下载依赖慢的解决方案(亲测有效)
查看>>
npm 安装依赖过程中报错:Error: Can‘t find Python executable “python“, you can set the PYTHON env variable
查看>>