7-Spring-AOP三种代理(切入)方法

使用Spring进行切面开发要先导入依赖

包括MVC里的AOP包

<dependency>
  <groupId>org.aspectj</groupId>
  <artifactId>aspectjweaver</artifactId>
  <version>1.9.4</version>
</dependency>

然后XML里的头部要加入: 

xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">

实现方法一:使用接口实现

  • 创建包:owner实现了car接口
  • inFrontProxy实现了spring接口:MethodBeforeAdvice(更多接口在文章后面讲)
    public class InFrontProxy implements MethodBeforeAdvice {
        @Override
        public void before(Method method, Object[] objects, Object o) throws Throwable {
            System.out.println("代理商在"+o.getClass().getName()+"的"+method.getName()+"前面执行了!");
        }
    }
    最后在beans.xml里注册了: 
    <bean name="infrontProxy" class="zhe.xin.proxy.InFrontProxy"/>
    <bean name="owner" class="zhe.xin.pojo.Owner"/>
    
    <!--方式1-->
    <aop:config>
        <!--需要切入的位置,第一个*是:返回类型,2是:包名.*可以匹配任意类名,3*是:所有类,4(..)是:任意参数类型-->
        <aop:pointcut id="pointcut" expression="execution(* zhe.xin.pojo.Owner.*(..))"/>
        <!--这里的意思是:我使用infrontProxy切入pointcut类-->
        <aop:advisor advice-ref="infrontProxy" pointcut-ref="pointcut"/>
    </aop:config>

实现方式二:使用bean.xml配置切入点(推荐使用此方法)

  • 在原有基础上创建新的类:
    public class Proxys {
        public void front(){
            System.out.println("在方法前面注入");
        }
        public void latter(){
            System.out.println("在方法后面注入");
        }
    }
  • beans.xml操作插入
    <bean name="infrontProxy" class="zhe.xin.proxy.InFrontProxy"/>
    <bean name="proxys" class="zhe.xin.proxy.Proxys"/>
    <bean name="owner" class="zhe.xin.pojo.Owner"/>
    
    <!--方法2-->
    <aop:config>
        <!--需要切入的位置,第一个*是:返回类型,2是:包名.*可以匹配任意类名,3*是:所有类,4(..)是:任意参数类型-->
        <aop:pointcut id="pointcut" expression="execution(* zhe.xin.pojo.Owner.*(..))"/>
        <!--导入代理类-->
        <aop:aspect ref="proxys">
            <!--在pointcut之前添加front代理-->
            <aop:before method="front" pointcut-ref="pointcut"/>
        </aop:aspect>
    </aop:config>
  • 在使用时还要一下几种切入方法:(后面讲解)

实现方法三: 使用注解开发:

  •   创建新的类(其他注解在后面讲解)
    @Aspect //表示此类为代理类
    public class NoteProxy {
        @Before("execution(* zhe.xin.pojo.Owner.*(..))")
        public void front(){
            System.out.println("在方法前面");
        }
    }

    然后在beans中注册

<bean name="noteProxy" class="zhe.xin.proxy.NoteProxy"/>
<!--方法3-->
<!--开启注解,并在之前要加入bean中-->
<aop:aspectj-autoproxy/>

最后运行方法(所有通用):

public class test {
    @Test
    public void tests(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//      //代理的是接口并非实现类,否则报错
        Car owner = context.getBean("owner", Car.class);
        owner.SellCar();

    }
}

不代理的情况下只输出:车主出售车辆

代理情况下输出:代理内容   车主出售车辆

 

补充其他切面注入:

 

​2023-10-08  18:29:24

 

posted @ 2023-10-08 18:30  哲_心  阅读(32)  评论(0)    收藏  举报