AOP是spring 的重要思想之一,面向切面编程。本篇文章,主要结合实例说明一下spring AOP实现的两种方式。xml配置和注解配置。
一、定义两个基本类。
Hello类和World类。
1. Hello类,类中有两个方法。
package service.serviceImpl;
import org.springframework.stereotype.Component;
@Component
public class Hello {
//定义个简单的方法
public void foo(){
System.out.println("执行Hellow组件的foo()方法");
}
public void addUser(String name,String pass){
System.out.println("执行Hellow组件的addUser()方法");
}
}
2. world类中的一个bar 方法
package service.serviceImpl;
import org.springframework.stereotype.Component;
@Component
public class World {
public void bar(){
System.out.println("执行组件的bar()方法");
}
}
二、xml配置方式实现AOP
1. 定义切面类:
package aspect;
import org.aspectj.lang.ProceedingJoinPoint;
public class AllAspect {
public void authority(){
System.out.println("--------模拟进行权限检查----");
}
public void release(){
System.out.println("------模拟方法之后释放资源-----");
}
2.spring 配置文件配置
<!-- ========================第一版====================== -->
<aop:config>
<!-- 将AllAspectBean转化为切面Bean。切面Bean的新名称是AllAspect。优先级是2 -->
<aop:aspect id="AllAspect" ref="allAspectBean" order="2">
<!-- 定义一个After增强处理,直接指定切入表达式。以切面Bean的release()方法作为增强处理方法 -->
<aop:after pointcut="execution(* service.serviceImpl.*.*(..))" method="release"/>
<aop:before pointcut="execution(* service.serviceImpl.*.*(..))" method="authority"/>
<aop:around pointcut="execution(* service.serviceImpl.*.*(..))" method="processTx"/>
</aop:aspect>
</aop:config>
<!-- 配置bean -->
<bean id="hello" class="service.serviceImpl.Hello"/>
<bean id="world" class="service.serviceImpl.World"/>
<bean id="allAspectBean" class="aspect.AllAspect"/>
3. client端调用。
package service.serviceImpl;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Client {
@Test
public void pulib() {
//创建Spring容器
/*ApplicationContext ctx = new
ClassPathXmlApplicationContext("applicationContext.xml");*/
ApplicationContext ctx = new
ClassPathXmlApplicationContext("applicationContext2.xml");
Hello p = (Hello)ctx.getBean("hello");
p.foo();
p.addUser("lizhenjuan", "very 棒棒哒");
}
}
三、注解方式实现AOP
1. @After注解
@Aspect
public class AfterTest {
@After("execution(* service.serviceImpl.*.*(..))")
public void release(){
System.out.println("------模拟方法之后释放资源-----");
}
}
2. @Before注解
@Component
@Aspect
public class AOPTest {
/* @Pointcut("execution(* org.crazyit.app.aspect.*.*(..))")
private void anyMethod(){}//定义一个切入点
@After("anyMethod()") */
//所有方法的执行作为切入点
@Before("execution(* service.serviceImpl.*.*(..))")
public void authority(){
System.out.println("--------模拟进行权限检查----");
}
}
3. spring xm文件中配置:
<!-- 指定自动搜索Bean组件、自动搜索切面类 -->
<context:component-scan base-package="service.serviceImpl,aspect">
<context:include-filter type="annotation" expression="org.aspectj.lang.annotation.Aspect"/>
</context:component-scan>
<aop:aspectj-autoproxy/>
4. 客户端调用如上面,输出结果和xml方式是相同的。
总结:
两种方式都要掌握,对比两种方式,注解方法更加的灵活,侵入性更低。