AOP
- 1.AOP:中文名称面向切面编程
- 2.英文名称:(Aspect Oriented Programming)
- 3.正常程序执行流程都是纵向执行流程
- 3.1 又叫面向切面编程,在原有纵向执行流程中添加横切面
- 3.2 不需要修改原有程序代码
- 3.2.1 高扩展性
- 3.2.2 原有功能相当于释放了部分逻辑.让职责更加明确.
- 4.面向切面编程是什么?
- 4.1 在程序原有纵向执行流程中,针对某一个或某一些方法添加通知,形成横切面过程就叫做面向切面编程.
- 5.spring 提供了 2 种 AOP 实现方式
- 5.1Schema-based
- 5.1.1 每个通知都需要实现接口或类
- 5.1.2 配置 spring 配置文件时在aop:config配置
- 5.2AspectJ
- 5.2.1 每个通知不需要实现接口或类
- 5.2.2 配置 spring 配置文件是在 < aop:config >的子标签< aop:aspect >中配置
- 5.1Schema-based
使用注解(基于 Aspect)
- spring 不会自动去寻找注解,必须告诉 spring 哪些包下的类中可能有注解
- 引入 xmlns:context
<context:component-scan base-package="com.yueyue.advice"></context:component-scan>
- @Component
2.1 相当于
2.2 如果没有参数,把类名首字母变小写,相当于<beanid=””/>
2.3@Component(“自定义名称”) - 实现步骤:
3.1 在 spring 配置文件中设置注解在哪些包中
<context:component-scan base-package="com.yueyue.advice,com.yueyue.test">
</cont ext:component-scan>
- 3.2 在 Demo 类中添加@Componet
- 3.2.1 在方法上添加@Pointcut(“”) 定义切点
@Component
public class Demo {
@Pointcut("execution(* com.yueyue.test.Demo.demo1())")
public void demo1() throws Exception{
System.out.println("demo1");
}
}
- 3.3 在通知类中配置
- 3.3.1@Component 类被 spring 管理
- 3.3.2@Aspect 相当于<aop:aspect/ >表示通知方法在当前类中
@Component
@Aspect
public class MyAdvice {
@Before("com.yueyue.test.Demo.demo1()")
public void mybefore(){
System.out.println("前置");
}
@After("com.yueyue.test.Demo.demo1()")
public void myafter(){
System.out.println("后置通知");
}
@AfterThrowing("com.yueyue.test.Demo.demo1()")
public void mythrow(){
System.out.println("异常通知");
}
@Around("com.yueyue.test.Demo.demo1()")
public Object myarround(ProceedingJoinPoint p) throws Throwable{ System.out.println("环绕-前置");
Object result = p.proceed();
System.out.println("环绕-后置");
return result;
}
}
cglib 动态代理
- cglib 优点:
1.1 基于字节码,生成真实对象的子类.
1.1.1 运行效率高于 JDK 动态代理.
1.2 不需要实现接口 - cglib 缺点:
2.1 非 JDK 功能,需要额外导入 jar - 使用 springaop 时,只要出现 Proxy 和真实对象转换异常
3.1 设置为 true 使用 cglib
3.2 设置为 false 使用 jdk(默认值)
<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
spring中加载properties文件
1.在src下新建xxx.properties文件
2. 在 spring 配置文件中先引入 xmlns:context,在下面添加
<context:property-placeholder location="classpath:db.properties"/>
- 在被Spring管理的类中通过@Value(“${key}”)取出properties中内容
3.1添加注解扫描
<context:component-scan
base-package="com.yueyue.service.impl"></context:compo nent-scan>
3.2 在类中添加
3.2.1key 和变量名可以不相同
3.2.2 变量类型任意,只要保证 key 对应的 value 能转换成这个类型就可以.
@Value("${demo}")
private String test;