首先先了解一下什么是AOP?
AOP是一种编程思想,不是java独有的,就像面向编程OOP那样,是一种编程思想.这种思想具体是什么呢?就是你可以偷偷的横插一脚干一些事情却不用改动原先的代码,这就是面向切面编程.比如我们的打印日志功能,或者常见的权限管理,事务管理等这些和业务代码不是很相关的,就可以采用这种形式.用的时候直接把代码给切入进来,然后依靠jdk或者cglib编译的时候动态生成代理对象,这个代理对象就包括了我们写的业务代码和增强类代码了,通过编译的时候把业务代码和增强代码结合起来.
下面看使用方法:
注意,面向切面必须要使用接口方式编程.至于为什么呢,因为生成代理的时候,这个代理对象要实现这个接口.
下面我们要做一个在UserServiceImpl类打印日志,而这个功能的实现就是通过面向切面来写的.
接口类:
public interface UserService { public void saveUser(); public void saveUser(String username); public void updateUser(); }
实现类,普通业务代码:
public class UserServiceImpl implements UserService{ @Override public void saveUser() { System.out.println("添加用户"); // 抛出异常的代码 // System.out.println(1 / 0); } @Override public void saveUser(String name ) { System.out.println("有参数的添加用户 : name"); } @Override public void updateUser() { System.out.println("修改用户"); } }
增强类,打印日志的功能:
public class MyAdvice {
public void log(){
System.out.println("记录日志...........................");
}
}
然后就是配置文件了,beans.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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 开启注解扫描 --> <context:component-scan base-package="org.tt"/> <bean id="userServiceImpl" class="org.tt.serviceimpl.UserServiceImpl"> </bean> <!-- aop增强类的xml配置方法,实例交给spring的IoC管理--> <bean id="myAdvice" class="org.tt.aop.advice.MyAdvice"></bean> <aop:config> <!--这里的ref引用就是上面配置MyAdvice类的id--> <aop:aspect ref="myAdvice"> <aop:before method="log" pointcut="execution(void org.tt.serviceimpl.UserServiceImpl.saveUser())" /> </aop:aspect>
<!--exection([修饰符] 返回值类型 包名.类名.方法名(参数)) exection是不可以省略的 --> </aop:config> </beans>
测试代码:
public class Test01 { public static void main(String[] args) { //配置文件的方式创建ApplicationContext ApplicationContext app = new ClassPathXmlApplicationContext("beans.xml"); //这里用到了AOP,必须用UserService接口类,不能用UserServiceImpl实现类 UserService userServiceImpl = (UserService)app.getBean("userServiceImpl"); userServiceImpl.saveUser(); } }
结果:

浙公网安备 33010602011771号