Spring的AOP学习

什么是AOP

AOP是面向切面的编程(Aspect Oriented Programming),是OOP的补充和完善。OOP引入继承、封装、多态等概念建立一套纵向的结构层次。但如果要在横向方面做些操作则比较复杂。比如两个类,想在两个类中添加日志功能。如果直接在类中编写日志代码则重复,不可复用。如果把日志功能提取为一个日志类,则增加了耦合性。AOP则是针对横向操作做的设计。AOP利用一种称为"横切"的技术,剖解开封装的对象内部,并将那些影响了多个类的公共行为封装到一个可重用模块(如日志模块),并将其命名为"Aspect",即切面。简单说就是那些与业务无关,却为业务模块所共同调用的逻辑或责任封装起来,便于减少系统的重复代码,降低模块之间的耦合度,并有利于未来的可操作性和可维护性。

 

相关概念

JointPoint(连接点):程序执行过程中的点,一般是调用的方法。

Pointcut(切入点):需要拦截的连接点。

Advice(通知):切入点上执行的处理,有before(前置),after(后置),afterReturning(最终),afterThrowing(异常),around (环绕)5种方式。

Aspect(切面):通常是一个类,里面可以定义切入点和通知。

 

下面做个小的Demo

1、编写一业务接口、实现业务类

package com.xhjz.business;

public interface IFlowerRing {
	void choiceStyle();
	void make();
	void polish();
}
package com.xhjz.business;

public class LoveRing implements IFlowerRing {

	@Override
	public void choiceStyle() {
		System.out.println("爱心钻戒——四叶草样式");
	}

	@Override
	public void make() {
		System.out.println("爱心钻戒——正在制作");
	}

	@Override
	public void polish() {
		System.out.println("爱心钻戒——抛光打磨");
	}

}

2、编写日志类

package com.xhjz.business;

public class TimePrint {
	
	public void print()
    {
        System.out.println("CurrentTime = " + System.currentTimeMillis());
    }
}

3、创建配置文件(spring.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: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-4.2.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">

	<bean id="lr" class="com.xhjz.business.LoveRing" />
	<bean id="tp" class="com.xhjz.business.TimePrint" />

	<aop:config>
		<aop:aspect id="aspect1" ref="tp">
			<aop:pointcut id="addAllMethod"
				expression="execution(* com.xhjz.business.IFlowerRing.*(..))" />
			<aop:before method="print" pointcut-ref="addAllMethod" />
			<aop:after method="print" pointcut-ref="addAllMethod" />
		</aop:aspect>
	</aop:config>

</beans>

4、测试

package com.xhjz.main;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.xhjz.business.IFlowerRing;

public class Yhjm {

	public static void main(String[] args) {

		ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");

		Object obj = ctx.getBean("lr");
		IFlowerRing lr = (IFlowerRing) obj;
		lr.choiceStyle();
		lr.make();
		lr.polish();
	}
}

5、结果输出

6、程序结构图

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值