• Spring-使用注解实现AOP(九)


    注解实现AOP代码流程变得极为简单,但是我们要明白其中的原理是何.

    在我们自定义实现的AOP中加入几个注解就可以实现

    注意点:

    要写切面的注解-->Aspect

    切入点可以直接写在增强上加上对应的注解就可以了.

    配置文件中加入识别注解自动代理的代码.---->[<aop:aspectj-autoproxy/>]

    目标对象不变userService和userServiceImpl

    package org.west.anno;
    
            import org.aspectj.lang.annotation.After;
            import org.aspectj.lang.annotation.Aspect;
            import org.aspectj.lang.annotation.Before;
    
    //切面注解
    @Aspect
    public class Anno {
        //   切入点可以直接写在增强上面
        @Before("execution(* org.west.service.UserServiceImpl.*(..))")
        public void before() {
            System.out.println("------>方法执行前");
    
        }
    
    
        @After("execution(* org.west.service.UserServiceImpl.*(..))")
        public void after() {
            System.out.println("------>方法执行后");
        }
    
    }

    注意注解before 和after的包要导对,是Aspectj的包.

    Spring的核心配置文件

    <?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: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/aop
             http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!--注册bean对象-->
        <bean id="userService" class="org.west.service.UserServiceImpl"/>
    <!--注解实现AOP的类-->
        <bean id="anno" class="org.west.anno.Anno"/>
    <!--识别注解自动代理-->
         <aop:aspectj-autoproxy/>
    
        
    </beans>

    测试类:

    public class TestDemo {
        @Test
        public void test() {
    
            ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext2.xml");
    
            UserService userService = (UserService) context.getBean("userService");
    
            userService.add();
    
        }

    AOP小结:

    • 本质就是动态代理

    • 需要到一个包,用来进行aop织入的包: aspectjweaver

    • 注意别遗漏了切面;

    • 三种实现AOP的方法

      • 使用SpringAPI来实现AOP

      • 使用自定义类来实现AOP

      • 使用注解实现AOP

  • 相关阅读:
    【设计模式】—— 单例模式Singleton
    【java开发系列】—— 深克隆和浅克隆
    【设计模式】—— 原型模式Prototype
    ArcMap 导入Excel坐标数据
    如何将XML文件导入Excel中
    ArcGIS API for Javascript之专题图的制作(四)热力图渲染(上)
    ArcGIS js api 手动构建FeatureLayer
    word怎样从第三页开始设置页码
    ArcGIS API for JS4.7加载FeatureLayer,点击弹出信息并高亮显示
    [转载]ArcGIS SERVER 9.3如何清除REST缓存
  • 原文地址:https://www.cnblogs.com/xiaoqiqistudy/p/11305378.html
Copyright © 2020-2023  润新知