Spring AOP 完全注解

来源:互联网 发布:淘宝pr 值多少 编辑:程序博客网 时间:2024/06/08 09:48

         AOP是面向切面编程,提出AOP的出发点是使得解耦的粒度更小,在方法的前后增加一些逻辑代码。下面是AOP的一些基本的概念:

        JoinPoint(连接点): 它定义在哪里(哪些点)加入你的逻辑功能,对于Spring AOP,Jointpoint指的就是Method. 

        PointCut(切入点的集合):即一组Joinpoint,(通过正则表达式去匹配)就是说一个Advice可能在多个地方织入。 

        Aspect(切面): 实际是Advice和Pointcut的组合。

        Advice(通知):所谓通知是指拦截到jointpoint之后所要做的事情就是通知即特定的Jointpoint处运行的代码。

        Target(目标对象):代理的目标对象即被通知的对象。 

        Weave(织入): 指将aspects应用到target对象并导致proxy对象创建的过程称为织入 。

        以一个例子来加以说明吧:

        @Component("hello")
        public class Bean{
               public void hello(){
                  System.out.println("hello spring");
               }
        }

        @Component("demo")
        @Aspect
        public class AspectDemo {
       @Before(value="execution(public void com.spring.Bean.hello(..))")
         public void save(){
              System.out.println("save ...");
         }
       }

        public class HelloSpring {

public static void main(String args[]){

ApplicationContext context =

   new ClassPathXmlApplicationContext("bean.xml");

Bean bean=(Bean)context.getBean("hello");

bean.hello();

       }
     }

    配置文件:

    <?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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--  <bean id="hello" class="com.spring.Bean"></bean> -->
<!-- <context:annotation-config /> -->
<context:component-scan base-package="com.spring"/>
<aop:aspectj-autoproxy />
</beans>

注:导入包的时候要注意, 一定要导入aopalliance.jar,否则会出现错误的。

       

原创粉丝点击