Spring中实现AOP的两种方式(二):

今天在昨天学习了三种方式的基础上又学习了spring中两种实现AOP的方式:

方式四:

bean.xml文件


    
    



   

    
    
    
    

    


MyAspect.java


import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

public class MyAspect implements MethodInterceptor {


    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        System.out.println("-----before---");
        Object obj = methodInvocation.proceed();
        System.out.println("-----after---");
        return obj;
    }
}

测试类


import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test04 {
    @Test
    public void testAOP04(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("beans04.xml");
        IUserServiceImpl us = ac.getBean("us",IUserServiceImpl.class);
        System.out.println(us.getAllUsers());
        System.out.println(us.deleteUser(1));
        System.out.println(us.saveUser(new Object()));
        System.out.println(us.updateUser(new Object()));
    }
}

运行结果为:

image.png

从图中可以看出仅仅delete()得到了增强.
该种方式比较灵活
image.png

如果出现上述问题,把xml放到resource包下即可
ps: 在高版的idea中 beans.xml只有在放在resource包下才能运行

方式五

beans.xml文件




    
    
    
        
            
            
            
        


    

MyAspect.java

package testAOP05;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

public class MyAspect {


    public void before(){
        System.out.println("********before**********");
    }

    public void after(){
        System.out.println("********after**********");
    }

}

测试类

    @Test
    public void testAOP05(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("beans05.xml");
        IUserServiceImpl ius = ac.getBean("us",IUserServiceImpl.class);
        System.out.println(ius.getAllUsers());
        System.out.println(ius.deleteUser(1));
        System.out.println(ius.saveUser(new Object()));
        System.out.println(ius.updateUser(new Object()));
    }

运行结果


image.png

相较于方法四 ,方法五不需要在切面类实现MethodInterceptor接口,更加的灵活

你可能感兴趣的:(Spring中实现AOP的两种方式(二):)