异常
在使用的时候,遇到了部分的异常,我用的是最新的Spring版本,Spring-4.2.5版本的,首先确保你的配置文件中引入了下面红色部分。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<span style="color:#ff0000;"> xmlns:aop="http://www.springframework.org/schema/aop"</span>
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
<span style="color:#ff0000;">http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd"</span>>
然后需要导入的包有几个:
1. aspectjrt.jar
2. aspectjweaver.jar
3. aopalliance-1.0.jar
我在使用的时候由于没有使用第三个jar包导致了异常信息如下:
警告: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.aop.config.internalAutoProxyCreator': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.aop.config.internalAutoProxyCreator': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1105)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1050)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
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:202)
at org.springframework.context.support.PostProcessorRegistrationDelegate.registerBeanPostProcessors(PostProcessorRegistrationDelegate.java:228)
at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:687)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:523)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.siti.spring20160315aop.MainTest.main(MainTest.java:9)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:163)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1098)
... 13 more
下面开始使用AspectJ进行切面配置
AspectJ注解方式进行切面配置
定义四个接口,下面让WangYang类实现这个Person的接口,并实现其中的方法。
package com.siti.spring20160315aop;
public interface Person {
void say();
void sayName(String name);
String saySth(String name);
void sayEx();
}
其中saySth这个方法设置了返回值,这个地方会被AfterReturning织入,然后sayEx方法为了测试故意利用空指针异常,测试AfterThrowing会不会被织入。
package com.siti.spring20160315aop;
public class WangYang implements Person{
@Override
public void say() {
System.out.println("wy!");
}
@Override
public void sayName(String name) {
System.out.println("name-->" + name);
}
@Override
public String saySth(String name) {
System.out.println("name-->" + name);
return name;
}
@Override
public void sayEx() {
Object obj = null;
obj.equals("1");
}
}
package com.siti.spring20160315aop;
import java.util.Arrays;
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.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
@Aspect
public class MyInterceptor {
@Pointcut("execution(* com.siti.spring20160315aop.WangYang.*(..))")
public void anyMethod(){}
@Before("anyMethod()")
public void checkMessage(JoinPoint joinPoint){
System.out.println("@Before-check!!!");
System.out.println("@Before-目标对象为:" + joinPoint.getTarget());
System.out.println("@Before-目标方法:" + joinPoint.getSignature().getName());
System.out.println("@Before-目标方法的参数:" + Arrays.toString(joinPoint.getArgs()));
}
@AfterReturning(pointcut = "anyMethod()", returning = "obj")
public void checkReturn(JoinPoint joinPoint, Object obj){
System.out.println("@AfterReturning-目标方法返回值:" + obj);
System.out.println("@AfterReturning-生成日志");
System.out.println("@AfterReturning-目标对象为:" + joinPoint.getTarget());
System.out.println("@AfterReturning-目标方法:" + joinPoint.getSignature().getName());
System.out.println("@AfterReturning-目标方法的参数:" + Arrays.toString(joinPoint.getArgs()));
}
@After("anyMethod()")
public void checkAfter(JoinPoint joinPoint){
System.out.println("@After-释放资源!");
System.out.println("@After-目标对象为:" + joinPoint.getTarget());
System.out.println("@After-目标方法:" + joinPoint.getSignature().getName());
System.out.println("@After-目标方法的参数:" + Arrays.toString(joinPoint.getArgs()));
}
@Around("anyMethod()")
public Object checkAround(ProceedingJoinPoint joinPoint) throws Throwable{
System.out.println("@Around!");
Object[] args = joinPoint.getArgs();
if(args != null && args.length > 0 && args[0].getClass() == String.class){
args[0] = "@Around" + args[0];
}
Object result = joinPoint.proceed(args);
if(result != null && result.getClass() == String.class){
result = result + "--wy";
}
return result;
}
@AfterThrowing(throwing = "ex", pointcut = "anyMethod()")
public void checkAfterThrowing(Throwable ex){
System.out.println("@AfterThrowing-异常抛出!");
System.out.println("@AfterThrowing-异常日志!");
}
}
<?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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
<aop:aspectj-autoproxy/>
<bean id = "inter" class = "com.siti.spring20160315aop.MyInterceptor"></bean>
<bean id = "wy" class = "com.siti.spring20160315aop.WangYang"></bean>
</beans>
测试:
package com.siti.spring20160315aop;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext20160315.xml");
Person wy = context.getBean("wy", Person.class);
wy.say();
wy.sayName("wangyang-");
String str = wy.saySth("hello--");
System.out.println("str的值:" + str);
// wy.sayEx();// 抛出异常的测试
}
}
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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
<aop:config>
<!-- 定义公共的切入点表达式 -->
<aop:pointcut expression="execution(* com.siti.spring20160315aopwithxml.WangYang.*(..))" id="pointCutCommon"/>
<!-- 定义切面,命名为 adviceRespect 优先级是2 ref:表示对谁进行增强处理-->
<aop:aspect id = "adviceRespect" ref = "inter" order="2">
<aop:before pointcut-ref="pointCutCommon" method="checkMessage"/>
<aop:after-returning pointcut-ref="pointCutCommon" method="checkReturn" returning="obj"/>
<aop:around pointcut-ref="pointCutCommon" method="checkAround"/>
<aop:after pointcut-ref="pointCutCommon" method="checkAfter"/>
</aop:aspect>
<aop:aspect id = "firstExecute" ref = "inter" order = "1">
<aop:after-throwing pointcut-ref="pointCutCommon" method="checkAfterThrowing" throwing="ex"/>
</aop:aspect>
</aop:config>
<bean id = "inter" class = "com.siti.spring20160315aopwithxml.MyInterceptor"></bean>
<bean id = "wy" class = "com.siti.spring20160315aopwithxml.WangYang"></bean>
</beans>
package com.siti.spring20160315aopwithxml;
import java.util.Arrays;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
public class MyInterceptor {
public void anyMethod(){}
public void checkMessage(JoinPoint joinPoint){
System.out.println("@Before-check!!!");
System.out.println("@Before-目标对象为:" + joinPoint.getTarget());
System.out.println("@Before-目标方法:" + joinPoint.getSignature().getName());
System.out.println("@Before-目标方法的参数:" + Arrays.toString(joinPoint.getArgs()));
}
public void checkReturn(JoinPoint joinPoint, Object obj){
System.out.println("@AfterReturning-目标方法返回值:" + obj);
System.out.println("@AfterReturning-生成日志");
System.out.println("@AfterReturning-目标对象为:" + joinPoint.getTarget());
System.out.println("@AfterReturning-目标方法:" + joinPoint.getSignature().getName());
System.out.println("@AfterReturning-目标方法的参数:" + Arrays.toString(joinPoint.getArgs()));
}
public void checkAfter(JoinPoint joinPoint){
System.out.println("@After-释放资源!");
System.out.println("@After-目标对象为:" + joinPoint.getTarget());
System.out.println("@After-目标方法:" + joinPoint.getSignature().getName());
System.out.println("@After-目标方法的参数:" + Arrays.toString(joinPoint.getArgs()));
}
public Object checkAround(ProceedingJoinPoint joinPoint) throws Throwable{
System.out.println("@Around!");
Object[] args = joinPoint.getArgs();
if(args != null && args.length > 0 && args[0].getClass() == String.class){
args[0] = "@Around" + args[0];
}
Object result = joinPoint.proceed(args);
if(result != null && result.getClass() == String.class){
result = result + "--wy";
}
return result;
}
public void checkAfterThrowing(Throwable ex){
System.out.println("@AfterThrowing-异常抛出!");
System.out.println("@AfterThrowing-异常日志!");
}
}