基于xml的spring AOP,简单实现

基于xml的spring AOP简单例子:

一、定义bean

                    package com.spring.aspect.log

                   //将此bean作为切面类

                    public class LogAspect {

                              public void log(){

                                   System.out.println("打日志");

                              }

                    }

              com.spring.test1包下有两个类:Person、Axe,将在这两个类中织入前置增强处理

                   public class Person {

                            public Axe axe;

                            public Axe getAxe() {

                                 return axe;

                              }

                             public void setAxe(Axe axe) {

                                 this.axe = axe;

                               }

                               public void printAxe(){

                                   System.out.println(axe.chop());

                              }

                    }

                    public class Axe {

                        public String chop(){

                                return "这是axe方法";

                        }

                    }

二、在spring配置文件中加入如下配置,

                  <bean id="person" class="com.spring.test1.Person">

                        <property name="axe" ref="axe"/>

                   </bean>

                   <bean id="axe" class="com.spring.test1.Axe"/>

                   <!-- 定义一个普通的bean,将此bean作为切面类 -->

                   <bean id="logAspect" class="com.spring.aspect.log.LogAspect"/>

  

                   <aop:config>

                         <!-- 定义切入点 ,com.spring.test1包下的所有类的方法,将被织入before增强处理-->

                         <aop:pointcut expression="execution(* com.spring.test1.*.*(..))" id="myPointcut"/>

                         <!-- 将logAspect定义切面类,并将其log方法定义为before增强处理 -->

                         <aop:aspect id="addLog" ref="logAspect">

        

                         <aop:before method="log"  pointcut-ref="myPointcut"/>

                    </aop:aspect>

  

                    </aop:config>

  注释:

         <aop:pointcut>用于定义通知,此节点放在<aop:config>下面,则定义全局的切入点,如果放在<aop:aspect>节点下,则只对该切面有效。

三、执行main方法,看结果

 public class GetSpringBeanByxml {

/**

* @param args

*/

public static void main(String[] args) throws Exception{

// TODO Auto-generated method stub

ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-config.xml");

Person person  =ctx.getBean("person",Person.class);

person.printAxe();

}

}

运行结果如下:

  打日志

  打日志

  这是axe方法

猜你喜欢

转载自collegeyuan.iteye.com/blog/2272671