Spring 使用AspectJ 的三种方式

一,使用JavaConfig

二,使用注解隐式配置

三,使用XML 配置

背景知识:

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

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

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 

类的结构 如 下图 所示

① 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 中 罢了

结构如下:

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

① 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 中 我有表现出这种形式

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

Spring 使用AspectJ的三种方式的更多相关文章

  1. spring创建bean的三种方式

    spring创建bean的三种方式: 1通过构造方法创建bean(最常用) 1.1 spring默认会通过无参构造方法来创建bean,如果xml文件是这样配置,则实体类中必须要有无参构造方法,无参构造 ...

  2. Spring静态注入的三种方式

    版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/chen1403876161/article/details/53644024Spring静态注入的三 ...

  3. Spring 循环依赖的三种方式(三级缓存解决Set循环依赖问题)

    本篇文章解决以下问题: [1] . Spring循环依赖指的是什么? [2] . Spring能解决哪种情况的循环依赖?不能解决哪种情况? [3] . Spring能解决的循环依赖原理(三级缓存) 一 ...

  4. spring生成EntityManagerFactory的三种方式

    spring生成EntityManagerFactory的三种方式 1.LocalEntityManagerFactoryBean只是简单环境中使用.它使用JPA PersistenceProvide ...

  5. Spring 实现事务的三种方式

    事务:保证数据的运行不会说A给B钱,A钱给了B却没收到. 实现事务的三种方式(重要代码): 1.aspectJ AOP实现事务: <bean id="dataSourceTransac ...

  6. SSH深度历险记(八) 剖析SSH核心原则+Spring依赖注入的三种方式

           于java发育.一类程序猿必须依靠类的其他方法,它是通常new依赖类的方法,然后调用类的实例,这样的发展问题new良好的班统一管理的例子.spring提出了依赖注入的思想,即依赖类不由程 ...

  7. SSH深度历险(八) 剖析SSH核心原理+Spring依赖注入的三种方式

           在java开发中,程序员在某个类中需要依赖其它类的方法,则通常是new一个依赖类再调用类实例的方法,这种开发存在的问题是new的类实例不好统一管理,spring提出了依赖注入的思想,即依 ...

  8. Spring配置dataSource的三种方式 数据库连接池

    1.使用org.springframework.jdbc.dataSource.DriverManagerDataSource 说明:DriverManagerDataSource建立连接是只要有连接 ...

  9. spring mvc handler的三种方式

    springmvc.xml 三种方式不能针对一个controller同时使用 <?xml version="1.0" encoding="UTF-8"?& ...

随机推荐

  1. Basic Skill

    Get current script path script=$() Check for root user ] ; then echo "current user is not root ...

  2. selenium+BeautifulSoup实现强大的爬虫功能

    sublime下运行 1 下载并安装必要的插件 BeautifulSoup selenium phantomjs 采用方式可以下载后安装,本文采用pip pip install BeautifulSo ...

  3. 基于轻量级ORM框架Dapper的扩展说明

    这里简单的介绍一下本人基于Dapper作的一些简单的扩展,供大家参考. 为何要使用这款框架,相信大家看到下面排名就清楚了 其实在各大网站上,我们大概都会看到这样的一个对比效果图,在超过500次poco ...

  4. Java - 9个处理异常的最佳准则

    其实工作这么久了一直都没搞清楚到底如何来处理异常,偶然看到一篇外文感觉还不错,便把它翻译了下来,原文链接位于本文末尾处. 在java中处理异常并不是一件简单的事,不止初学者觉得它难以理解甚至连有经验的 ...

  5. 利用JavaScript来切换样式表

    切换样式表 html页 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http:/ ...

  6. 使用Sidecar将Node.js引入Spring Cloud

    网上看到的一篇文章,觉得写得挺好,现转载于此,以方便需要的网友查阅. 该文章介绍了非JAVA语言提供的应用集成到Spring Cloud的这样一个实现,以便我们使用其他语言作为参考. 感谢原作者分享, ...

  7. js 对于回车时间的监听,提交表单

    // ------ 监听回车事件 -----------------// document.onkeydown=keyDownSearch; function keyDownSearch(e) { / ...

  8. jsp、freemarker、velocity区别详解

    详见:http://blog.yemou.net/article/query/info/tytfjhfascvhzxcyt172 在java领域,表现层技术主要有三种:jsp.freemarker.v ...

  9. poj3723 MST好题 kruskal

    #include<iostream> #include<cstring> #include<cstdio> #include<algorithm> us ...

  10. 媒体查询media参数以及其兼容性问题

    一.设置meta标签 在使用媒体查询media之前我们需要先设置meta标签,对设备的缩放等参数进行设定. <!--设置缩放和绘制--> <meta name="viewp ...