Spring Aop基础总结
什么是AOP:
Aop技术是Spring核心特性之中的一个,定义一个切面。切面上包括一些附加的业务逻辑代码。在程序运行的过程中找到一个切点,把切面放置在此处,程序运行到此处时候会运行切面上的代码。这就是AOP.。
AOP的实现机制是什么:
Aop是基于动态代理模式实现的,被代理类实现过接口,能够用反射包里的InvocationHandler和Proxy实现。被代理类没有实现过接口。能够用cglib生成二进制码获得代理类。
AOP有什么用途:
Aop用处许多,比方在程序中加入事物,加入日志等。
AOP怎样使用:
能够通过注解的方式和xml配置的方式使用Aop,例如以下是配置的Aop.
使用AOP。在UserDao的save方法前后,切入程序:
UserDao
package com.dao;
public class UserDao {
public void save(){
System.out.println("in save");
}
}
切面程序,在save方法运行前后要运行的程序:
package com.aop;
import org.aspectj.lang.ProceedingJoinPoint;
public class ServiceAop {
public void before(){
System.out.println("in before");
}
public void after(){
System.out.println("in after");
}
public void around(ProceedingJoinPoint pjp) throws Throwable{
System.out.println("around in before");
pjp.proceed();
System.out.println("around in after");
}
}
applicationContext.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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"> <bean id="userDao" class="com.dao.UserDao"></bean> <bean id="serviceAop" class="com.aop.ServiceAop"></bean> <aop:config> <aop:pointcut expression="execution(* com.dao.*.*(..))" id="cutId"/> <aop:aspect ref="serviceAop"> <aop:before method="before" pointcut-ref="cutId"/> <aop:after method="after" pointcut-ref="cutId"/> <aop:around method="around" pointcut-ref="cutId"/> </aop:aspect> </aop:config> </beans>
測试类:
package com.dao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao ud=(UserDao) ac.getBean("userDao");
ud.save();
}
}

浙公网安备 33010602011771号