Announcement Announcement Module
Collapse
No announcement yet.
Spring AOP and AspectJ Integration with EJB3 Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Spring AOP and AspectJ Integration with EJB3

    Hi,
    Can anyone give me an headstart on how to integrate Spring AOP ans AspectJ in EJB3.
    So far I have figured out the following related to this.

    EJB Stateless Session Bean. I am injecting the SaveCreditCardInfoDAO bean into my Controller EJB. But while I am calling the method using the instance I have injected, nothing is getting logged.
    Code:
    /**
     * Session Bean implementation class Controller
     */
    @Stateless(name="Controller")
    @TransactionManagement(TransactionManagementType.CONTAINER)
    @Interceptors(SpringBeanAutowiringInterceptor.class)
    public class Controller implements ControllerRemote, ControllerLocal {
    	
    	@Resource(name=CCSConstants.CCS_DATASOURCE_JNDI)
    	DataSource ccsDataSource;
    	
    	@Resource
    	private SessionContext ejbContext;
    	
    	@Autowired
    	private SaveCardInfoDAO saveCardInfo;
    	
        /**
         * Default constructor. 
         */
        public Controller() {
            // TODO Auto-generated constructor stub
        }
    
        /**
    	 * Exposed Message to insert the Credit Card Info into the database. 
    	 */
        @TransactionAttribute(TransactionAttributeType.REQUIRED)
    	public void insertCardInfo(CreditCardDO ccdo){
        	
        	//SaveCardInfoDAO saveCardInfo = new SaveCardInfoDAO(ccsDataSource);
    		try{
    			saveCardInfo.setDataSource(ccsDataSource);
    			saveCardInfo.openConnection(false);
    			saveCardInfo.insertCardInfo(ccdo);
    			System.out.println("Insert Success !!!");
    		}
    		catch(SQLException e){
    			ejbContext.setRollbackOnly();
    			System.out.println("Insert Failure !!!");
    		}
    		finally{
    			saveCardInfo.closeConnection();
    		}
    	}
    }
    beanRefContext.xml
    Code:
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
    <beans>
    	<bean id="factoryKey"
    		class="org.springframework.context.support.ClassPathXmlApplicationContext">
    		<constructor-arg value="aopContext.xml" />
    	</bean>
    </beans>

    aopContext.xml
    Code:
    <?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-3.0.xsd
    		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
    
       <aop:aspectj-autoproxy />
       
       <bean id="creditCardAdvice" class="com.fedex.ccs.advice.CCSCreditCardInfoAdvice" />
       <!-- <bean id="creditCardDO" class="com.fedex.ccs.domain.CreditCardDO" />  -->
       <bean id="saveCardInfo" class="com.fedex.ccs.dao.SaveCardInfoDAO" />   
    </beans>
    Advice Class
    Code:
    @Aspect
    public class CCSCreditCardInfoAdvice {
    	private static CCSLoggerInterface myCcsLogger = 
    		CCSLogger.getLogger(CCSCreditCardInfoAdvice.class);
    	
    	/**
    	 * Constructor
    	 */
    	public CCSCreditCardInfoAdvice(){}
    	
    	// All the methods within com.fedex.bean package, with any return type 
    	// belong to the Pointcut humanMethods()
    	@Pointcut("execution(* *.*.*(..))")
    	public void creditCardMethods(){}
    	
    	// Method to be executed before the respective Pointcut method is run.  
    	@Before("creditCardMethods()")
    	public void logBeforeMessage(JoinPoint jp) throws Throwable {
    		// TODO Auto-generated method stub
    		myCcsLogger.info("************* Method Before '"+jp.getSignature().getName()+"' Called **************");
    	}
    	
    	// Method to be executed after the respective Pointcut method is run.  
    	@After("creditCardMethods()")
    	public void logAfterMessage(JoinPoint jp) throws Throwable {
    		// TODO Auto-generated method stub		
    		myCcsLogger.info("************* Method After '"+jp.getSignature().getName()+"' Called **************");
    	}
    	
    	@Around("creditCardMethods()")
    	public Object logAroundMessage(ProceedingJoinPoint pjp) throws Throwable {
    		// TODO Auto-generated method stub
    		myCcsLogger.info("************* Method '"+pjp.getSignature().getName()+"' Getting Called **************");
    		Object output = pjp.proceed();
    		myCcsLogger.info("************* Method Output is '"+output+"' **************");
    		myCcsLogger.info("************* Method '"+pjp.getSignature().getName()+"' Completed **************");
    		return output;
    	}
    }
    ApplicationUtil Class used to load the logger xml file.
    Code:
    public class ApplicationUtil {	
    	static{
    		init();
    	}
    
    	public static void init(){
    		DOMConfigurator.configure("resource/ccslogger.xml");
    	}
    }
    When I run my client it gives me following error.
    Code:
    Caused By: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.context.support.ClassPathXmlApplicationContext]: Constructor threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'creditCardAdvice' defined in class path resource [aopContext.xml]: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class com.fedex.ccs.advice.CCSCreditCardInfoAdvice
    	at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:162)
    	at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:108)
    	at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:280)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1003)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:907)
    	Truncated. see log file for complete stacktrace
    
    Caused By: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'creditCardAdvice' defined in class path resource [aopContext.xml]: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class com.fedex.ccs.advice.CCSCreditCardInfoAdvice
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:965)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:911)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    	at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
    	Truncated. see log file for complete stacktrace
    
    Caused By: java.lang.NoClassDefFoundError: Could not initialize class com.fedex.ccs.advice.CCSCreditCardInfoAdvice
    	at sun.reflect.GeneratedConstructorAccessor89.newInstance(Unknown Source)
    	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    	at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    	at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:147)
    	at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:74)
    	Truncated. see log file for complete stacktrace
    If I remove following line from aopContext.xml then the application runs fine but does not log anything.
    Code:
    <bean id="creditCardAdvice" class="com.fedex.ccs.advice.CCSCreditCardInfoAdvice" />
    All these files and classes are in the same Eclipse project. Only SaveCreditCardInfoDAO is in different project but still its instance is getting injected into the EJB.

    Please advice !!!

    Regards
    Damodar

  • #2
    Caused By: java.lang.NoClassDefFoundError: Could not initialize class com.fedex.ccs.advice.CCSCreditCardInfoAdvice
    Well the error is pretty clear...have you double-checked that the class is in the correct package and that it is correctly exported in the WEB-INF/classes folder of the war?
    If yes, then probably you have a classloader issue...do you use Maven to manage dependencies/compile/build/deploy?

    Comment


    • #3
      Thanks for the reply.
      Here is the thing. I have the advice class in a simple java project "ccs_commons". And this project has been added as the dependency for EJB project "ccs_ejb" which has all the spring configuration files. Additionally I have created an EAR project "ccs_ear" for the all the projects and I deploy this ear project on the weblogic server.
      I do not use Maven.

      The .class file of the class in question is getting generated in the "bin" folder in "ccs_commons" project. I donot have WEB-INF folder in "ccs_ejb" project as I do not have any web related content like jsps/servlets. All the .class files of the ejb project go into "build" folder.

      What I do not understand here is that if Spring can inject one class residing in a different project that has been added as the dependency for the spring project, then why cant it inject another class.
      Does class loader issue means that the class dependent on the "CCSCreditCardInfoAdvice" gets loaded first and it does not find the class it depends on and throws this exception? Any guidance as to how can I alter the order of loading classes.

      Regards
      Damodar

      Comment


      • #4
        Here is the first part of complete stack trace.

        Code:
        > 
        <May 23, 2011 10:42:00 AM EDT> <Warning> <EJB> <BEA-010065> <MessageDrivenBean threw an Exception in onMessage(). The exception was:
         javax.ejb.NoSuchEJBException: Bean is already undeployed..
        javax.ejb.NoSuchEJBException: Bean is already undeployed.
        	at weblogic.ejb.container.manager.BaseEJBManager.preInvoke(BaseEJBManager.java:153)
        	at weblogic.ejb.container.manager.StatelessManager.preInvoke(StatelessManager.java:132)
        	at weblogic.ejb.container.internal.BaseLocalObject.preInvoke(BaseLocalObject.java:242)
        	at weblogic.ejb.container.internal.BaseLocalObject.preInvoke(BaseLocalObject.java:189)
        	at weblogic.ejb.container.internal.StatelessLocalObject.__WL_preInvoke(StatelessLocalObject.java:52)
        	Truncated. see log file for complete stacktrace
        > 
        <May 23, 2011 10:42:00 AM EDT> <Notice> <EJB> <BEA-010015> <Error occurred while marking transaction for rollback: java.lang.IllegalStateException: Cannot mark the transaction for rollback as it has been rolledback. xid=BEA1-0026E920146A3057A4BD, status=Rolled back. [Reason=weblogic.transaction.internal.AppSetRollbackOnlyException: setRollbackOnly called on transaction].
        java.lang.IllegalStateException: Cannot mark the transaction for rollback as it has been rolledback. xid=BEA1-0026E920146A3057A4BD, status=Rolled back. [Reason=weblogic.transaction.internal.AppSetRollbackOnlyException: setRollbackOnly called on transaction]
        	at weblogic.transaction.internal.TransactionImpl.throwIllegalStateException(TransactionImpl.java:1882)
        	at weblogic.transaction.internal.TransactionImpl.setRollbackOnly(TransactionImpl.java:557)
        	at weblogic.ejb.container.internal.BaseLocalObject.handleSystemException(BaseLocalObject.java:868)
        	at weblogic.ejb.container.internal.BaseLocalObject.handleSystemException(BaseLocalObject.java:794)
        	at weblogic.ejb.container.internal.BaseLocalObject.preInvoke(BaseLocalObject.java:267)
        	Truncated. see log file for complete stacktrace
        > 
        <May 23, 2011 10:42:00 AM EDT> <Warning> <EJB> <BEA-010065> <MessageDrivenBean threw an Exception in onMessage(). The exception was:
         javax.ejb.EJBTransactionRolledbackException: EJB Exception: ; nested exception is: com.oracle.pitchfork.interfaces.LifecycleCallbackException: Failure to invoke public void org.springframework.ejb.interceptor.SpringBeanAutowiringInterceptor.autowireBean(javax.interceptor.InvocationContext) on bean class class org.springframework.ejb.interceptor.SpringBeanAutowiringInterceptor_s85z0p_Impl with args: [com.bea.core.repackaged.springframework.jee.intercept.InterceptionMetadata$LifecycleEventCallbackInvocationContext@1013892]; nested exception is: com.oracle.pitchfork.interfaces.LifecycleCallbackException: Failure to invoke public void org.springframework.ejb.interceptor.SpringBeanAutowiringInterceptor.autowireBean(javax.interceptor.InvocationContext) on bean class class org.springframework.ejb.interceptor.SpringBeanAutowiringInterceptor_s85z0p_Impl with args: [com.bea.core.repackaged.springframework.jee.intercept.InterceptionMetadata$LifecycleEventCallbackInvocationContext@1013892].
        javax.ejb.EJBTransactionRolledbackException: EJB Exception: ; nested exception is: com.oracle.pitchfork.interfaces.LifecycleCallbackException: Failure to invoke public void org.springframework.ejb.interceptor.SpringBeanAutowiringInterceptor.autowireBean(javax.interceptor.InvocationContext) on bean class class org.springframework.ejb.interceptor.SpringBeanAutowiringInterceptor_s85z0p_Impl with args: [com.bea.core.repackaged.springframework.jee.intercept.InterceptionMetadata$LifecycleEventCallbackInvocationContext@1013892]; nested exception is: com.oracle.pitchfork.interfaces.LifecycleCallbackException: Failure to invoke public void org.springframework.ejb.interceptor.SpringBeanAutowiringInterceptor.autowireBean(javax.interceptor.InvocationContext) on bean class class org.springframework.ejb.interceptor.SpringBeanAutowiringInterceptor_s85z0p_Impl with args: [com.bea.core.repackaged.springframework.jee.intercept.InterceptionMetadata$LifecycleEventCallbackInvocationContext@1013892]
        	at weblogic.ejb.container.internal.BaseLocalObject.handleSystemException(BaseLocalObject.java:799)
        	at weblogic.ejb.container.internal.BaseLocalObject.preInvoke(BaseLocalObject.java:267)
        	at weblogic.ejb.container.internal.BaseLocalObject.preInvoke(BaseLocalObject.java:189)
        	at weblogic.ejb.container.internal.StatelessLocalObject.__WL_preInvoke(StatelessLocalObject.java:52)
        	at com.fedex.ccs.ejb.session.Controller_5zf69k_ControllerLocalImpl.insertCardInfo(Controller_5zf69k_ControllerLocalImpl.java:32)
        	Truncated. see log file for complete stacktrace
        
        Caused By: com.oracle.pitchfork.interfaces.LifecycleCallbackException: Failure to invoke public void org.springframework.ejb.interceptor.SpringBeanAutowiringInterceptor.autowireBean(javax.interceptor.InvocationContext) on bean class class org.springframework.ejb.interceptor.SpringBeanAutowiringInterceptor_s85z0p_Impl with args: [com.bea.core.repackaged.springframework.jee.intercept.InterceptionMetadata$LifecycleEventCallbackInvocationContext@1013892]
        	at com.bea.core.repackaged.springframework.jee.inject.Jsr250Metadata.invokeLifecycleMethod(Jsr250Metadata.java:335)
        	at com.bea.core.repackaged.springframework.jee.intercept.InterceptionMetadata.invokeLifecycleMethods(InterceptionMetadata.java:565)
        	at com.bea.core.repackaged.springframework.jee.intercept.InterceptionMetadata$AdvisorChainProxyControl.invokeLifecycleMethod(InterceptionMetadata.java:534)
        	at sun.reflect.GeneratedMethodAccessor103.invoke(Unknown Source)
        	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        	Truncated. see log file for complete stacktrace

        Comment


        • #5
          Here is second part of complete stack trace

          Code:
          Caused By: java.lang.reflect.InvocationTargetException
          	at sun.reflect.GeneratedMethodAccessor111.invoke(Unknown Source)
          	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
          	at java.lang.reflect.Method.invoke(Method.java:597)
          	at com.bea.core.repackaged.springframework.jee.inject.Jsr250Metadata.invokeLifecycleMethod(Jsr250Metadata.java:332)
          	at com.bea.core.repackaged.springframework.jee.intercept.InterceptionMetadata.invokeLifecycleMethods(InterceptionMetadata.java:565)
          	Truncated. see log file for complete stacktrace
          
          Caused By: org.springframework.beans.factory.access.BootstrapException: Unable to initialize group definition. Group resource name [classpath*:beanRefContext.xml], factory key [null]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'factoryKey' defined in URL [file:/C:/Users/Damodar/Documents/Damodar/Fedex_Credit_Card_Services/CSS_Prototype_Code/ccs_ejb/build/classes/beanRefContext.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.context.support.ClassPathXmlApplicationContext]: Constructor threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'creditCardAdvice' defined in class path resource [aopContext.xml]: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class com.fedex.ccs.advice.CCSCreditCardInfoAdvice
          	at org.springframework.beans.factory.access.SingletonBeanFactoryLocator.useBeanFactory(SingletonBeanFactoryLocator.java:389)
          	at org.springframework.ejb.interceptor.SpringBeanAutowiringInterceptor.getBeanFactoryReference(SpringBeanAutowiringInterceptor.java:156)
          	at org.springframework.ejb.interceptor.SpringBeanAutowiringInterceptor.getBeanFactory(SpringBeanAutowiringInterceptor.java:137)
          	at org.springframework.ejb.interceptor.SpringBeanAutowiringInterceptor.doAutowireBean(SpringBeanAutowiringInterceptor.java:117)
          	at org.springframework.ejb.interceptor.SpringBeanAutowiringInterceptor.autowireBean(SpringBeanAutowiringInterceptor.java:97)
          	Truncated. see log file for complete stacktrace
          
          Caused By: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'factoryKey' defined in URL [file:/C:/Users/Damodar/Documents/Damodar/Fedex_Credit_Card_Services/CSS_Prototype_Code/ccs_ejb/build/classes/beanRefContext.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.context.support.ClassPathXmlApplicationContext]: Constructor threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'creditCardAdvice' defined in class path resource [aopContext.xml]: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class com.fedex.ccs.advice.CCSCreditCardInfoAdvice
          	at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:288)
          	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1003)
          	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:907)
          	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)
          	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
          	Truncated. see log file for complete stacktrace
          
          Caused By: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.context.support.ClassPathXmlApplicationContext]: Constructor threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'creditCardAdvice' defined in class path resource [aopContext.xml]: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class com.fedex.ccs.advice.CCSCreditCardInfoAdvice
          	at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:162)
          	at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:108)
          	at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:280)
          	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1003)
          	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:907)
          	Truncated. see log file for complete stacktrace
          
          Caused By: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'creditCardAdvice' defined in class path resource [aopContext.xml]: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class com.fedex.ccs.advice.CCSCreditCardInfoAdvice
          	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:965)
          	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:911)
          	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)
          	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
          	at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
          	Truncated. see log file for complete stacktrace
          
          Caused By: java.lang.NoClassDefFoundError: Could not initialize class com.fedex.ccs.advice.CCSCreditCardInfoAdvice
          	at sun.reflect.GeneratedConstructorAccessor85.newInstance(Unknown Source)
          	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
          	at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
          	at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:147)
          	at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:74)
          	Truncated. see log file for complete stacktrace

          Comment

          Working...
          X