Spring AOP功能的实现

主要有两种方式:一种是基于XML Schema的设置,一种是基于Annotation的支持

基于XML Schema的前置通知(现在LogBeforeAdvice不需要实现MethodBeforeAdvice)

LogBeforeAdvice.java
public class LogBeforeAdvice {

    public void before(JoinPoint joinPoint) {

        System.out.println(joinPoint.getSignature().getName()+",start.............LogBeforeAdvice");

    }

}
applicationContext.xml
<bean id="logBeforeAdvice" class="com.edu.cug.LogBeforeAdvice"></bean>

    <aop:config>

        <aop:aspect id="logBeforeAspect" ref="logBeforeAdvice">

            <aop:pointcut id="LogbeforePointcut" expression="execution(* hello*(..))"/>

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

        </aop:aspect>

    </aop:config>

测试程序:

View Code
public class AopTest {



    public static void main(String[] args) {

        BeanFactory factory = new ClassPathXmlApplicationContext(

                "applicationContext.xml");

        IHello bean = (IHello) factory.getBean("IHello");

        bean.hello1("AOP1");

        bean.hello2("AOP2");

    }

}

测试结果

hello1,start.............LogBeforeAdvice

hello1,AOP1

hello2,start.............LogBeforeAdvice

hello2,AOP2
  • 基于Annotation的前置通知
  • 定义切面:
    LogBeforeAdvice.java
    @Aspect
    
    public class LogBeforeAdvice {
    
        
    
        @Pointcut("execution(* com.edu.cug.IHello.*(..)) ")
    
        public void anymethod(){} 
    
        
    
        @Before("anymethod()")
    
        public void before(JoinPoint joinPoint) {
    
            System.out.println(joinPoint.getSignature().getName()
    
                    + ",start.............LogBeforeAdvice");
    
        }
    
    }
    applicationContext.xml
    <bean id="IHello" class="com.edu.cug.IHelloImpl"></bean>
    
        <bean id="logBeforeAdvice" class="com.edu.cug.LogBeforeAdvice"></bean>
    
        <aop:aspectj-autoproxy/>

    测试程序

    AopTest.java
    public class AopTest {
    
        public static void main(String[] args) {
    
            BeanFactory factory = new ClassPathXmlApplicationContext(
    
                    "applicationContext.xml");
    
            IHello bean = (IHello) factory.getBean("IHello");
    
            bean.hello1("AOP1");
    
            bean.hello2("AOP2");
    
        }
    
    }

    测试结果

    hello1,start.............LogBeforeAdvice
    
    hello1,AOP1
    
    hello2,start.............LogBeforeAdvice
    
    hello2,AOP2

    在Spring2.x中要声明Pointcut,主要包括两个部分:Pointcut表达式(expression)与Pointcut签名(signature)


你可能感兴趣的:(spring aop)