Spring (11)-use Aspectj aspect configuration and XML configuration file to implement aspect Programming

Source: Internet
Author: User

Spring (11)-use Aspectj aspect configuration and XML configuration file to implement aspect Programming
Exception

Some exceptions were encountered during use. I used the latest Spring version, Spring-4.2.5 version. First, make sure that the following red section is introduced in your configuration file.

 
   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.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
 

Then there are several packages to import:

 

1. aspectjrt. jar

2. aspectjweaver. jar

3. aopalliance-1.0.jar

 

When I was using the third jar package, the exception information was as follows:

 

Warning Exception encountered during context initialization-canceling 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/MethodInterceptorException 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/MethodInterceptorat 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.
 
  
(ClassPathXmlApplicationContext. java: 139) at org. springframework. context. support. ClassPathXmlApplicationContext.
  
   
(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/MethodInterceptorat 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
  
 


 

The following describes how to use AspectJ for configuration.

 

 

AspectJ annotation Configuration

 

Define four interfaces. Let the WangYang class implement the Person interface and implement the method.

 

package com.siti.spring20160315aop;public interface Person {void say();void sayName(String name);String saySth(String name);void sayEx();}

 

 

In this example, the return value is set for the sayth method, which will be woven by AfterReturning. Then, to test whether the sayEx method intentionally uses a null pointer exception, it will test whether AfterThrowing will be woven.

 

package com.siti.spring20160315aop;public class WangYang implements Person{@Overridepublic void say() {System.out.println("wy!");}@Overridepublic void sayName(String name) {System.out.println("name-->" + name);}@Overridepublic String saySth(String name) {System.out.println("name-->" + name);return name;}@Overridepublic void sayEx() {Object obj = null;obj.equals("1");}}

 

The implementation of AspectJ for Aspect-Oriented Programming is mainly implemented in the following way. The after notification is mainly used to release resources, the afterReturning notification can change the return value, and the afterThrowing notification can capture exceptions to generate exception records, the before notification can be used for parameter verification.
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. befor E; import org. aspectj. lang. annotation. pointcut; @ Aspectpublic 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-the target object is:" + joinPoint. getTarget (); System. out. println ("@ Before-target method:" + joinPoint. getSignature (). getName (); System. out. println ("@ Before-parameter of the target method:" + Arrays. toString (joinPoint. getArgs ();} @ AfterReturning (pointcut = "anyMethod ()", returning = "obj") public void checkReturn (JoinPoint joinPoint, Object obj) {System. out. println ("@ AfterReturning-returned value of the target method:" + obj); System. out. prin Tln ("@ AfterReturning-log generation"); System. out. println ("@ AfterReturning-target object:" + joinPoint. getTarget (); System. out. println ("@ AfterReturning-target method:" + joinPoint. getSignature (). getName (); System. out. println ("@ AfterReturning-parameter of the target method:" + Arrays. toString (joinPoint. getArgs ();} @ After ("anyMethod ()") public void checkAfter (JoinPoint joinPoint) {System. out. println ("@ After-release resources! "); System. out. println ("@ After-the target object is:" + joinPoint. getTarget (); System. out. println ("@ After-target method:" + joinPoint. getSignature (). getName (); System. out. println ("@ After-target method parameter:" + 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-an exception is thrown! "); System. out. println (" @ AfterThrowing-exception log! ");}}

 

The configuration file needs to "register" the section class we wrote in the configuration file ".

 

 
 
  
  
 
Test:

 

 

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. saysomething ("hello --"); System. out. println ("str value:" + str); // wy. sayEx (); // a test that throws an exception }}




 

XML configuration file Method

 

The configuration method based on the configuration file is basically similar to the method described above. Here we just list the changes and do not introduce them.

The configuration file is as follows:

 

 
 
  
  
  
  
 

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-the target object is:" + joinPoint. getTarget (); System. out. println ("@ Before-target method:" + joinPoint. getSignature (). getName (); System. out. println ("@ Before-parameter of the target method:" + Arrays. toString (joinPoint. getArgs ();} public void checkReturn (JoinPoint joinPoint, Object obj) {System. out. println ("@ AfterReturning-returned value of the target method:" + obj); System. out. println ("@ AfterReturning-generate log"); System. out. println ("@ AfterReturn Ing-target object: "+ joinPoint. getTarget (); System. out. println ("@ AfterReturning-target method:" + joinPoint. getSignature (). getName (); System. out. println ("@ AfterReturning-parameter of the target method:" + Arrays. toString (joinPoint. getArgs ();} public void checkAfter (JoinPoint joinPoint) {System. out. println ("@ After-release resources! "); System. out. println ("@ After-the target object is:" + joinPoint. getTarget (); System. out. println ("@ After-target method:" + joinPoint. getSignature (). getName (); System. out. println ("@ After-target method parameter:" + 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-an exception is thrown! "); System. out. println (" @ AfterThrowing-exception log! ");}}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.