AOP
AOP 面向切面编程
AOP的功能是基于IOC的功能之上,所有我们必须先引用IOC的的全部jar包
AOP和aspects是构成AOP的基础,所以必须得引入两个jar包
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.3.25.RELEASE</version>
</dependency>
AOP为了解决代码重用的问题
在方法的前面或者后面切入一段代码
1.切面 一个普通的类,任何的类都可以变成一个切面
2.切入点 切入点
3.关注点 目标 将这段代码切入到哪个地方去 可以是一个具体的方法 也可以是一个类中的全部方法 也可以是一个包中的所有类
4.切入方式 可以在前面加一个 也可以在后面加一个 可以在前后加多个切入点
5.注解 启用注解的功能 applicationcontext.xml
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
@Component
@Aspect
切入点表达式
* 返回值类型
* 表示一层
.* 表示多层
.. 表示任意多个参数
AOP编程 一般在开发过程 只用在三个场合
1.打日志
2.事务处理
3.读写分离
配置文件面向切面编程
1.先将类加入到IOC容器中
<bean id="hang" class="com.blb.Hang"></bean>
2.配置切面
<aop:config>
<aop:aspect ref="hang">
<aop:pointcut id="xiaohong" expression="execution(* com.blb.UserDao.*(..))"></aop:pointcut>
<aop:before method="sayHello" pointcut-ref="xiaohong"></aop:before>
</aop:aspect>
</aop:config>
Cglib代理
public static void main(String[] args) {
Enhancer enhancer = new Enhancer(); //使用cglib的enhancer方法
enhancer.setSuperclass(Hello.class); //需要被切的类
enhancer.setCallback(new Rule()); //设置切面规则
Hello enen = (Hello)enhancer.create(); //生成代理类
System.out.println(enen.getClass());
enen.sayhello();
}
//切面规则 将AOPS类切入Hello类
public class Rule implements MethodInterceptor {
private AOPS aops = new AOPS();
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
aops.before();
Object result = methodProxy.invokeSuper(o,objects);
aops.after();
return result;
}
}