spring中AOP基本配置

我们上篇文章讲了两种代理,基于接口的代理和基于子类的代理。但在spring中,创建代理对象是由框架帮我们做的,我们只需要告诉spring:需要对哪些类中的哪些方法进行拦截,什么时候增强,具体怎么增强。

那么下面我们就在bean.xml中配置这些信息。

这是我们的通知类:

package com.dimples.log;

public class MyLog {
	public void printLog(){
		System.out.println("打印日志!");
	}
}

这是bean.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	   xmlns:context="http://www.springframework.org/schema/context"
	   xmlns:p="http://www.springframework.org/schema/p"
	   xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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/aop
       					   http://www.springframework.org/schema/aop/spring-aop.xsd
       					   ">
 
	<bean id="cust" class="com.hehe.service.impl.CustomerServiceImpl"/>
        <!--第一步,把通知类交给spring来管理-->
	<bean id="logger" class="com.hehe.log.MyLog"/>
        <!--第二步u,导入aop相关约束,如上-->
        <!--第三步,配置一个切面,id用于给这个切面作为标识,ref用于引用通知类-->
	<aop:config>
		<aop:aspect id="logAspect" ref="logger">
        <!--第四步,指定通知具体方法及其作用时间,然后再指定切入点,切入点表达式格式:
                关键字:execution(表达式)
                访问修饰符 返回值类型 全包名类名方法名及其形参
        -->
			<aop:before method="printLog" pointcut="execution(public void com.hehe.service.impl.CustomerServiceImpl.saveCustomer())"/>
		</aop:aspect>
	</aop:config>
</beans>

测试:

                ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
		ICustomerService c = (ICustomerService) ac.getBean("cust");
		c.saveCustomer();

 运行结果:

log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
打印日志!
保存方法执行了!

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值