您的位置:首页 > 编程语言 > Java开发

Spring面向切面编程AOP

2017-05-25 17:49 561 查看
AOP就是对目标方法运行之前、运行中、运行之后、运行之后返回、运行中异常的切入。在切入中运行出现的任何异常,并不影响目标方法的运行。

1、定义一个接口【IServiceName.java】

package com.zuk.hl.test.springAOP.annotation;
/**
* <p> Title: className </p>
* <p> Description: classDescription </p>
* <p> Copyright: openlo.cn Copyright (C) 2017 </p>
*
* @author huangl
* @since 2017年5月25日 下午4:48:55
*/
public interface IServiceName {

String setName(String name);

}


2、实现接口类【ServiceName.java】
package com.zuk.hl.test.springAOP.annotation;

import org.springframework.stereotype.Component;

/**
* <p> Title: className </p>
* <p> Description: classDescription </p>
* <p> Copyright: openlo.cn Copyright (C) 2017 </p>
*
* @author huangl
* @since 2017年5月24日 下午3:16:48
*/

@Component
public class ServiceName implements IServiceName{

private String name;

public String setName(String name) {
System.out.println("ServiceName.setName():"+name);
this.name = name;
return this.name + "ldygo";
}

public boolean throwExcption() throws Exception{
if(true){
System.out.println("throwExcption()");
throw new Exception("spring aop ThrowAdvice演示");
}

return false;
}

@Override
public String toString(){
return "[ServiceName:{name:"+this.name+"}]";
}

}


3、实现接口类【ServiceName2.java】
package com.zuk.hl.test.springAOP.annotation;

import org.springframework.stereotype.Component;

/**
* <p> Title: className </p>
* <p> Description: classDescription </p>
* <p> Copyright: openlo.cn Copyright (C) 2017 </p>
*
* @author huangl
* @since 2017年5月24日 下午3:16:48
*/

@Component
public class ServiceName2 implements IServiceName{

private String name;

public String setName(String name) {
System.out.println("ServiceName2.setName():"+name);
this.name = name;
return this.name + ".LDYGO.";
}

public boolean throwExcption() throws Exception{
if(true){
System.out.println("throwExcption()");
throw new Exception("spring aop ThrowAdvice演示");
}

return false;
}

@Override
public String toString(){
return "[ServiceName2:{name:"+this.name+"}]";
}

}


4、定一个AOP接口【IAOPService.java】
package com.zuk.hl.test.springAOP.annotation;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

/**
* <p> Title: IService </p>
* <p> Description: 面向AOP编程接口 </p>
* <p> Copyright: openlo.cn Copyright (C) 2017 </p>
*
* @author huangl
* @since 2017年5月24日 下午4:19:15
*/

public abstract class IAOPService {

//切入点
@Pointcut("")
public void pointcut(){

}

/**
* <br>前置通知
* <br>Object[] getArgs:返回目标方法的参数
* <br>Signature getSignature:返回目标方法的签名
* <br>Object getTarget:返回被织入增强处理的目标对象
* <br>Object getThis:返回AOP框架为目标对象生成的代理对象
*
* <p>注意:</p>
* <br>即便是存在异常抛出,也不影响原来方法的进入
*
* */
@Before("pointcut()")
public void beforeAdvice(JoinPoint call){

}

/**
* <br>后置通知
* <br>目标方法如何结束(保存成功完成和遇到异常中止两种情况),它都会被织入
* */
@After("pointcut()")
public void afterAdvice(JoinPoint joinPoint){

}

/**
* 返回后通知
* @param joinPoint
* @param retVal
*
* <br>增强处理处理只有在目标方法成功完成后才会被织入
* */
@AfterReturning(returning="returnObj",pointcut="pointcut()")
public void afterReturnAdvice(JoinPoint call,Object returnObj){

}

/**
* <br>环绕通知
* <br>ProceedingJoinPoint类型,该类是JoinPoint的子类。
*
* <br>不修改目标(方法)的参数
* Object result1 = call.proceed();
*
* <br>可通过修改call.getArgs()的方法修改目标(方法)的参数
* Object result2 = call.proceed(call.getArgs());
*
* */
@Around("pointcut()")
public Object aroundAdvice(ProceedingJoinPoint call) throws Throwable{
return null;
}

//抛出异常通知
@AfterThrowing(pointcut="pointcut()", throwing="ex")
public void afterThrowingAdvice(JoinPoint joinPoint, Exception ex){

}

}


5、AOP接口的实现类【AOPServiceImpl.java】
package com.zuk.hl.test.springAOP.annotation;

import java.sql.ResultSet;
import java.util.Arrays;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
* <p> Title: AOPServiceImpl </p>
* <p> Description: 面向AOP切面编程实现 </p>
* <p> Copyright: openlo.cn Copyright (C) 2017 </p>
*
* @author huangl
* @since 2017年5月24日 下午4:25:14
*/

//声明这是一个组件
@Component("AOPServiceImpl")
//声明这是一个切面Bean
@Aspect
public class AOPServiceImpl extends IAOPService{

//具体某一个接口
@Pointcut("execution(* com.zuk.hl.test.springAOP.annotation.IServiceName.setName(String))")
//具体到方法
//@Pointcut("execution(* com.zuk.hl.test.springAOP.annotation.ServiceName.setName(String))")
//具体到类
//@Pointcut("execution(* com.zuk.hl.test.springAOP.annotation.ServiceName..*(..))")
@Override
public void pointcut() {
// TODO Auto-generated method stub
}

@Override
public void beforeAdvice(JoinPoint call) {

System.out.println("-->"+call);
// System.out.println("被切入的对象:"+call.getTarget());
System.out.println("被切入的参数:"+Arrays.toString(call.getArgs()));

// Object[] args = call.getArgs();
// String str = (String)args[0];
// System.out.println("传入的参数为:"+str);

// str = str + "XXX";

String className = call.getTarget().getClass().getName();
String methodName = call.getSignature().getName();

System.out.println("【注解-前置通知】:" + className + "类的" + methodName+ "方法开始了");

}

@Override
public void afterAdvice(JoinPoint joinPoint) {
System.out.println("AOPServiceImpl.afterAdvice()");
}

@Override
public void afterReturnAdvice(JoinPoint call, Object returnObj) {
System.out.println("AOPServiceImpl.afterReturnAdvice()");
System.out.println("返回值:"+returnObj);
}

@Override
public Object aroundAdvice(ProceedingJoinPoint call) throws Throwable {
System.out.println("AOPServiceImpl.aroundAdvice()");

Object result = null;
//this.beforeAdvice(call);// 相当于前置通知
try {
System.out.println(">>>>>>>>>>>>>>>>>>"+call.getArgs()[0]);

Object obj = call.proceed();
System.out.println("obj01:"+obj);

call.getArgs()[0] = "HHIHIH";

//result = call.proceed();
result = call.proceed(call.getArgs());
System.out.println("obj02:"+result);

//this.afterReturnAdvice(); // 相当于后置通知
} catch (Throwable e) {
//this.afterThrowingAdvice(); // 相当于异常抛出后通知
throw e;
} finally {
//this.afterReturnAdvice(); // 相当于最终通知
System.out.println(">>>>>>>>>>>>>>最终");
}
return result;
}

@Override
public void afterThrowingAdvice(JoinPoint joinPoint, Exception ex) {
System.out.print("AOPServiceImpl.afterThrowingAdvice()");
System.out.println("->"+ex.getMessage());
}

}


6、测试类【ServiceAspectTestJunit.java】
package com.zuk.hl.test.springAOP.annotation;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
* <p> Title: ServiceAspectTestJunit </p>
* <p> Description: 注释的方式使用AOP切面测试程序  </p>
* <p> Copyright: openlo.cn Copyright (C) 2017 </p>
*
* @author huangl
* @since 2017年5月24日 下午3:09:34
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContextAOP2.xml")
public class ServiceAspectTestJunit {

@Autowired
private ServiceName us;

@Autowired
private ServiceName2 us2;

@Test
public void testAOP() throws Exception{

//System.in.read();

//Thread.sleep(1000);

us.setName("hello.");
//String str = us.getName();
System.out.println("设置的值-->"+us.toString());
//us.throwExcption();

us2.setName("biu.");
System.out.println("设置的值2-->"+us2.toString());

}

}


7、配置文件【applicationContextAOP2.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:context="http://www.springframework.org/schema/context" 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-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd" >

<!-- 激活组件扫描功能,在包cn.ysh.studio.spring.aop及其子包下面自动扫描通过注解配置的组件 -->
<context:component-scan base-package="com.zuk.hl.test.springAOP."/>
<!-- 激活自动代理功能 -->
<aop:aspectj-autoproxy proxy-target-class="true"/>

</beans>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: