spring面向切面编程的方式实现
第一步: 要代理的类.接口+实现类
第二步 代理类要实现相应的接口的方法
第三步 配置xml文件:spring-context.xml
1.注册相关的类(代理类+被代理类的实现的接口)
2.配置切入点
3.配置通知
4.配置切面
第四步 调用 :调用切面对象 生成代理的接口对象
首先导包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>
一.辅助代理类
1 package com.yztc.aop1; 2 3 import org.springframework.aop.AfterReturningAdvice; 4 import org.springframework.aop.MethodBeforeAdvice; 5 6 import java.lang.reflect.Method; 7 8 /** 9 * 辅助代理类 10 * @author bindu 11 * 12 */ 13 public class SleepHelper implements MethodBeforeAdvice,AfterReturningAdvice{ 14 15 @Override 16 public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable { 17 System.out.println("睡觉之猴撸一把"); 18 19 } 20 21 @Override 22 public void before(Method method, Object[] args, Object target) throws Throwable { 23 System.out.println("睡觉之钱撸两把"); 24 } 25 }
二.接口,实现类
1 package com.yztc.aop1; 2 3 public interface SleepDao { 4 public void asleep(); 5 public void bsleep(); 6 }
1 package com.yztc.aop1; 2 3 /** 4 * 创建要代理的对象 5 * 生成代理类 6 */ 7 public class SleepDaoImpl implements SleepDao { 8 @Override 9 public void asleep() { 10 System.out.println("紧急集合"); 11 } 12 13 @Override 14 public void bsleep() { 15 System.out.println("迎接胜利吧!"); 16 } 17 }
三.配置xml文件:spring-context.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> 5 <!--一.注册实现类对象--> 6 <bean id="sleepDao" class="com.yztc.aop1.SleepDaoImpl"/> 7 <!--代理类注册--> 8 <bean id="helper" class="com.yztc.aop1.SleepHelper"/> 9 <!--二. 配置 切入点--> 10 <bean id="pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut"> 11 <property name="pattern" value=".*sleep"/> 12 </bean> 13 <!--三. 配置 通知--> 14 <bean id="advisor" class="org.springframework.aop.support.DefaultPointcutAdvisor"> 15 <!--helper 对象是代理类--> 16 <property name="advice" ref="helper"/> 17 <!--切入 点--> 18 <property name="pointcut" ref="pointcut"/> 19 </bean> 20 <!--四. 配置切面--> 21 <bean id="aspect" class="org.springframework.aop.framework.ProxyFactoryBean"> 22 <!--代理的目标的实现类--> 23 <property name="target" ref="sleepDao"/> 24 <!--代理的接口对象--> 25 <property name="proxyInterfaces" value="com.yztc.aop1.SleepDao"/> 26 <!--代理的通知类--> 27 <property name="interceptorNames" value="advisor"/> 28 </bean> 29 30 </beans>
1 package com.yztc.aop1; 2 3 import org.springframework.context.support.ClassPathXmlApplicationContext; 4 5 6 public class TestMain { 7 public static void main(String[] args) { 8 ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml"); 9 SleepDao dao = (SleepDao) context.getBean("aspect"); 10 dao.bsleep(); 11 12 } 13 }