当前位置: 移动技术网 > IT编程>开发语言>Java > Spring-使用注解实现AOP(九)

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

2019年08月05日  | 移动技术网IT编程  | 我要评论

注解实现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

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网