先来了解一下spring配置方式的优缺点:
1.基于注解的配置优点是更短、更简洁,缺点是配置嵌入到各个文件中,比较分散不易于管理。
2.而XML配置优点是配置比较集中、方便管理,缺点是配置冗长、不够简洁。
AOP说白了就是在不改变原有业务的情况下对业务就行增强
下面来举个例子:
首先先创建持久层dao的文件:
package aopBao.dao;
public interface TestDao {
public void add();
public void updata();
public void delete();
}
package aopBao.dao;
import org.springframework.stereotype.Repository;
@Repository("testDao") //持久层
public class TestDaoImpl implements TestDao{
@Override
public void add() {
System.out.println("添加");
}
@Override
public void updata() {
System.out.println("更改");
}
@Override
public void delete() {
System.out.println("删除");
}
}
然后再创建切面(Aspext)文件:
package aopBao.aspect;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Aspect //定义切面
@Component //交由Spring容器管理
public class MyAspect {
@Pointcut("execution(* aopBao.dao.*.*(..))") //注解切入点表达式(匹配的是dao包的任意类任意方法)
public void myPointCut() {
}
@Before("myPointCut()") //前置通知 myPointCut()是切入点的定义方法
public void beFore(){
System.out.println("运行前置通知");
}
@After("myPointCut()") //后置通知
public void after(){
System.out.println("运行后置通知");
}
}
其中 定义切入点pointcut,通知增强哪些方法, "execution(* aopBao.dao.*.*(..))" 是定义切入点表达式, 该切入点表达式的意思是匹配dao包中任意类的任意方法的执行。
1.其中 execution()是表达式的主体,第一个*表示的是返回类型,使用*代表所有类型;
2后面第二个*表示的是类名,使用*代表匹配包中所有的类;
3.第三个*表示的是方法名,使用*表示所有方法; 后面(..)表示方法的参数,其中“..”表示任意参数。 另外,注意第一个*与包名之间有一个空格。
再配置xml文件:
<?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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 指定需要扫描的包,使注解生效 -->
<context:component-scan base-package="aopBao"/>
<!-- 启动基于注解的AspectJ支持 -->
<aop:aspectj-autoproxy/>
</beans>
最后测试一下:
package aopBao.test;
import aopBao.dao.TestDao;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class test {
public static void main(String[] args) {
ClassPathXmlApplicationContext cpxac =
new ClassPathXmlApplicationContext("config/applicationContext.xml");
TestDao t1 = (TestDao) cpxac.getBean("testDao"); //获取交由spring管理的id
t1.add();
System.out.println("=======================================================================");
t1.updata();
System.out.println("=======================================================================");
t1.delete();
}
}
运行结果: