Spring 配置通知AOP

介绍一下有关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啦

  • 6
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值