介绍一下有关AOP的基本概念
1,切面:也就是我们平常所说的系统辅助功能,例如:日志,权限管理,异常处理,事务等等。他不是系统的主要业务功能。
2:切点:他是系统的主要功能,例如登录注册,查询等等。主业务只是关注于完成核心业务处理。
3:通知:切点确定了使用切面的位置,但是什么时候应用就由通知来决定,比如在切点方法执行之前或者后。
4:织入:切点与切面都是独立的类,通过织入才能让切面切入切点,所以,织入就是配置。
如何使用。
我们只需要导入相应的jar包:aopalliance.jar与aspectjweaver.jar,随后我们只需要编写相对应的类继承对应的接口就行了。例如:如下就是一个前置通知,他会在对应的方法执行之前执行。
public class LoggerBefore implements MethodBeforeAdvice{
private static final Logger log=Logger.getLogger(LoggerBefore.class);
public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable {
log.info("开始添加学生....");
}
}
不过在此之前要配置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" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- collaborators and configuration for this bean go here --> <context:component-scan base-package="com.lijie"/> <!-- <aop:aspectj-autoproxy/> 开启对Aspectj注解的支持--> <bean id="myLogger" class="com.lijie.aop.Mylogger"></bean> <aop:config> <aop:pointcut expression="execution(* com.lijie.service.*.*(...))" id="pointcut"/> <!--通知切点切入advice-ref的指定的bean里面的方法。切入位置在前还是后由切面的的接口决定. --> <aop:advisor advice-ref="loggerbefore" pointcut-ref="pointcut"/> </aop:config> </beans>
先定义切面,在定义切点,最后在通知切点织入通知。最关键的是<aop:config>正是他实现了主业务的切点位置切入的功能;<aop:pointcut>子节点用于定义切点,expression是匹配方法就是你要在主业务的那个方法,我这里的是在service包下的所有类,所有方法的任意形参。只要是匹配上的都将作为切点,
接下来就是编写一个测试类来测试一下那。
public class Test {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("aplicationContext.xml");
UserService service=(UserService)context.getBean("userService");
service.addUser();
}
}
以上就是配置一个简单的aop啦