Spring---面向切面编程(aop)实例

Spring---面向切面编程(aop)实例
AOP(Aspect Oriented Programming)面向切面编程:
1、产生的原因:为了将程序中重复的代码抽取出来,秉承程序设计“高内聚,低耦合”的思想。
比如:
Session开启事务

查询代码

session提交事务
头部和尾部的代码(开启事务和提交事务),每个test方法中都是相同的代码,每次重复编写这些代码显得很浪费时间,所以就可以将头部和尾部的代码抽取出去,程序员只需要负责编写中间的部分代码就可以了,这也是"面向切面编程"的思想。
2、AOP可以做什么?
事务:开启事务、提交事务的代码抽取出来
日志:在方法开始之前,加入一句代码,表示进入了这个方法,在方法结束之前,加入一句代码,表示离开了这个方法。
安全性校验:在方法开始之前,进行安全性校验,在方法结束之后,进行安全性校验
3、AOP关键字
切点:指定在哪个方法上插入代码
切面:由多个切点构成的切点的规则
目标:用来切切点的java类,在方法上要插入的代码
通知:告诉你要切的方法,是切头还是切尾,还是头尾都切
前置通知、后置通知、环绕通知、异常通知、引入通知

AOP实例如下:
1、新建一个java工程,添加spring-3.1支持
2、新建com.etc.service包,在包下新建HelloService.java类:
package com.etc.service;

public class HelloService {
	public void sayHello(){
		System.out.println("hello");
	}
}
3、新建com.etc.aop包,在包下新建MyTarget.java类:
package com.etc.aop;

public class MyTarget {
	public void before(){
		System.out.println("方法开始");
	}
	public void after(){
		System.out.println("方法结束");
	}
}
4、配置applicationContext.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:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">
<!-- 1、定义命名空间aop 
xmlns:aop="http://www.springframework.org/schema/aop"
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd-->
<!-- 2、配置aop -->
<aop:config>
	<!-- 定义一个切面,由多个切点构成  -->
	<aop:aspect id="myAspect" ref="myTarget">
		<!-- 定义一个切点  规则:对com.etc.service包的所有类下的所有方法下的所有参数进行切点 -->
		<aop:pointcut id="myPointCut" expression="execution (* com.etc.service.*.*(..) )" />
		
		<!-- 定义一个通知:在方法之前进行的操作 -->
		<aop:before method="before" pointcut-ref="myPointCut"/>
		<!-- 定义一个通知:在方法之后进行的操作 -->
		<aop:after method="after" pointcut-ref="myPointCut"/>
	</aop:aspect>
</aop:config>
<!-- 定义一个目标  用来切切点的类,指定要插入的代码 -->
<bean name="myTarget" class="com.etc.aop.MyTarget"></bean>

<bean name="helloService" class="com.etc.service.HelloService"></bean>

</beans>
 
  
 
  
 
 
5、新建一个测试类HelloServiceTest.java类:
package com.etc.test;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.etc.service.HelloService;

public class HelloServiceTest {
	@Test
	public void test1(){
		//1、加载spring配置
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
		//2、通过配置文件获取所需要的类,不需要新建类的对象
		HelloService helloService = (HelloService) context.getBean("helloService");
		//3、调用这个类的方法
		helloService.sayHello();
	}
}
运行结果如下:
方法开始
hello
方法结束




猜你喜欢

转载自blog.csdn.net/zz2713634772/article/details/77036426
今日推荐