Spring 使用AspectJ的三种方式

Spring 使用AspectJ 的三种方式

一,使用JavaConfig

二,使用注解隐式配置

三,使用XML 配置

背景知识:

Spring 使用AspectJ的三种方式

Spring 使用AspectJ的三种方式

注意 使用AspectJ 的 时候 要导入相应的Jar 包

Spring 使用AspectJ的三种方式

嗯 昨天还碰到了这样的问题:

Caused by: java.lang.IllegalArgumentException: error at ::0 can't find referenced pointcut ArithmeticPointCut

 java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.context.event.internalEventListenerProcessor': Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: error at ::0 can't find referenced pointcut ArithmeticPointCut
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:564)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:128)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:108)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:251)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
... 25 more
Caused by: java.lang.IllegalArgumentException: error at ::0 can't find referenced pointcut ArithmeticPointCut
at org.aspectj.weaver.tools.PointcutParser.parsePointcutExpression(PointcutParser.java:317)
at org.springframework.aop.aspectj.AspectJExpressionPointcut.buildPointcutExpression(AspectJExpressionPointcut.java:217)
at org.springframework.aop.aspectj.AspectJExpressionPointcut.checkReadyToMatch(AspectJExpressionPointcut.java:190)
at org.springframework.aop.aspectj.AspectJExpressionPointcut.getClassFilter(AspectJExpressionPointcut.java:169)
at org.springframework.aop.support.AopUtils.canApply(AopUtils.java:220)
at org.springframework.aop.support.AopUtils.canApply(AopUtils.java:279)
at org.springframework.aop.support.AopUtils.findAdvisorsThatCanApply(AopUtils.java:311)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findAdvisorsThatCanApply(AbstractAdvisorAutoProxyCreator.java:119)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findEligibleAdvisors(AbstractAdvisorAutoProxyCreator.java:89)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.getAdvicesAndAdvisorsForBean(AbstractAdvisorAutoProxyCreator.java:70)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:346)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:298)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:423)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1633)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
... 39 more

Error

更换了Jar 包  从 1.5 --> 换到了 1.8.10 就好了  注意  aspectj 和asectjweaver 要版本对应

JavaConfig 

类的结构 如 下图 所示

Spring 使用AspectJ的三种方式

① Java Config

代码如下:  其中要注意@EnableAspectJAutoProxy(proxyTargetClass=true)   默认值为 false  只有开启proxyTargetClass 才会实现AspectJ 的切片功能

 package com.myth.spring.aop.config;

 import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component; @Component
@EnableAspectJAutoProxy(proxyTargetClass=true)
@ComponentScan(basePackages="com.myth.spring.aop")
public class ArithmeticCaculatorConfig { }

ArithmeticCaculatorConfig

② Service 类下面就是最基本的 实现类 代码如下:

注意每个类前 要加上@Component的标签

 package com.myth.spring.aop.service;

 public interface IArithmeticCaculator {
public int add(int a ,int b);
public int sub(int a ,int b);
public int mul(int a ,int b);
public int div(int a ,int b);
}

IArithmeticCaculator

 package com.myth.spring.aop.service.impl;

 import org.springframework.stereotype.Component;

 import com.myth.spring.aop.service.IArithmeticCaculator;
import com.myth.springAOP.exception.NotZeroException;
@Component
public class ArithmeticCaculatorImpl implements IArithmeticCaculator{ @Override
public int add(int a, int b) {
System.out.println(a + b);
return a + b;
} @Override
public int sub(int a, int b) {
return a - b;
} @Override
public int mul(int a, int b) {
return a * b;
} @Override
public int div(int a, int b) {
if (b == 0) {
throw new NotZeroException("除数不能为空");
}
return a / b;
}
}

ArithmeticCaculatorImpl

③ Aspect 类

这个类中 需要注意的点就比较多了

我在其中只写了  @Before , @After 和 @AfterReturning

1.定义为@Aspect

2.定义@Pointcut  根据这个切点来描写方法

3.写其中的@Before 或者其他Aspect 方法

当我们调用JoinPoint 时  要 joinpoint  要选择org.aspectj.lang.JoinPoint

 package com.myth.spring.aop.service.aspect;

 import java.util.Arrays;

 import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component; @Component
@Aspect
/**
* 要在Config中配置@EnableAspectJAutoProxy(proxyTargetClass=true) 默认为false
* joinpoint 要选择org.aspectj.lang.JoinPoint
*
*/
public class LoggingAspect {
@Pointcut("execution(* com.myth.spring.aop.service.impl.ArithmeticCaculatorImpl.*(int , int ))")
public void ArithmeticPointCut() {} @Before("ArithmeticPointCut()")
public void before(JoinPoint joinpoint) {
String method = joinpoint.getSignature().getName();
System.out.println("The method "+method+" begins with "+Arrays.asList(joinpoint.getArgs()));
} /* @After(value= "ArithmeticPointCut()")
public void After(JoinPoint joinpoint) {
String method = joinpoint.getSignature().getName();
System.out.println("The method "+method+" ends with ");
}*/ @AfterReturning(value="ArithmeticPointCut()", returning = "result")
public void afterReturn(JoinPoint joinPoint ,Object result) {
String method = joinPoint.getSignature().getName();
System.out.println("The method "+method+" ends with " + result);
}
}

LoggingAspect

④ Junit 类

关于Junit 类 可以关注  我的这篇帖子

使用Spring的隐式注解和装配以及使用SpringTest框架

http://www.cnblogs.com/mythdoraemon/p/7533553.html

代码如下:

 package com.myth.spring.aop.test;

 import static org.junit.Assert.*;

 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; import com.myth.spring.aop.config.ArithmeticCaculatorConfig;
import com.myth.spring.aop.service.IArithmeticCaculator;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=ArithmeticCaculatorConfig.class)
public class TestAspect { @Autowired
private IArithmeticCaculator iArithmeticCaculator; @Test
public void test() {
iArithmeticCaculator.add(1, 2);
} }

TestAspect

注解注入

注解注入大部分与JavaConfig 很像 , 其实就是把Java Config 的内容去不都写到了XML 中 罢了

结构如下:

Spring 使用AspectJ的三种方式

我们跟上面的结构对应起来

① Java Config  这里应该是容器 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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
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-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
<!-- 添加自动扫描机制 -->
<context:component-scan base-package="com.myth.spring.aop.annotion"></context:component-scan> <!-- 添加切面机制 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy> </beans>

applicationContext.xml

② Service 类 与上面的代码一样  就不重复写了

③ Aspect 类 也与 前面的一样 这回我写的是Around 方法

Around 其实包括了其他4种切面方式

 /**
* 对于环绕通知来说, 连接点的参数类型必须是 ProceedingJoinPoint . 它是 JoinPoint 的子接口, 允许控制何时执行,
* 是否执行连接点.
* 环绕通知必须有返回值,返回值为proceedingJoinPoint.proceed() 的结果
* @param proceedingJoinPoint
*/
@Around(value = "ArithmeticPointCut()")
public Object Around(ProceedingJoinPoint proceedingJoinPoint) {
String method = proceedingJoinPoint.getSignature().getName();
Object result = null;
try {
//相当于前置通知
System.out.println("The method " + method + " begins with " + Arrays.asList(proceedingJoinPoint.getArgs()));
result = proceedingJoinPoint.proceed();
//相当于后置返回通知
System.out.println("The method " + method + " ends with " + result);
} catch (NotZeroException e) {
//相当于异常通知
System.out.println("The method " + method + " occur an exception: " + e);
throw new NotZeroException("除数不能为空");
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
//相当于后置通知
System.out.println("The method " + method + " end");
}
return result;
}

LoggingAspect#Around

④ Test 类

这回Test 类 跟上面的会有些不同

@ContextConfiguration(locations= {"classpath:applicationContext.xml"})

这样子加载ApplicationContext 资源

 package com.myth.spring.aop.annotion.test;

 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; import com.myth.spring.aop.annotion.service.IArithmeticCaculator; @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:applicationContext.xml"})
public class TestAspect {
@Autowired
private IArithmeticCaculator iArithmeticCaculator; @Test
public void testAdd() {
iArithmeticCaculator.add(1, 2);
} @Test
public void testDiv() {
iArithmeticCaculator.div(1, 0);
}
}

TestAspect

XML配置

XML 配置其实就是把所有的切面方法写到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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
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-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd"> <bean id="arithmeticCalculator" class="com.myth.spring.AOP.xml.ArithmeticCalculatorImpl">
</bean> <bean id="loggingAspect" class="com.myth.spring.AOP.xml.LoggingAspect"></bean> <bean id="validation" class="com.myth.spring.AOP.xml.Validation"></bean> <!-- 配置AOP -->
<aop:config>
<aop:pointcut expression="execution(* com.myth.spring.AOP.xml.ArithmeticCalculator.*(.. ))"
id="pointcut"/>
<aop:aspect order="2" ref="loggingAspect" >
<aop:before method="beforeMethod" pointcut-ref="pointcut"/>
<!-- <aop:after method="afterMethod" pointcut-ref="pointcut"/> -->
<aop:after-returning method="afterReturningMethod" pointcut-ref="pointcut" returning="result"/>
<aop:after-throwing method="afterThrowingMethod" pointcut-ref="pointcut" throwing="ex"/>
</aop:aspect>
<aop:aspect order="1" ref="validation" >
<aop:before method="validate" pointcut-ref="pointcut"/>
</aop:aspect>
</aop:config> </beans>

applicationContext.xml

总结:  我是建议用第一种方法

首先界面干净清晰 不用太依赖于xml文件

其次 因为我这个案例比较小, 如果切面有很多  其他的写法会有很多切面在XML 中存在  对了 我们可以设置Order 属性来确定切面的顺序, 在 XML 中 我有表现出这种形式

当然了  每种写法都可以, 大家择其喜欢的吧

上一篇:Object.prototype.toString.call(obj)使用方法以及原理


下一篇:nginx 服务器重启命令,关闭