Announcement Announcement Module
Collapse
No announcement yet.
Context initialization failing due to inner class usage Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Context initialization failing due to inner class usage

    Hello,

    I have a bean which i want to validate using my Validator implementation.
    This Validator implementation i have declared as inner class.
    But a context initialization failed exception is occuring with the details as follows:

    Code:
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creati
    ng bean with name 'customerFormValidator' defined in ServletContext resource [/W
    EB-INF/app-servlet.xml]: Instantiation of bean failed; nested exception is org
    .springframework.beans.BeanInstantiationException: Could not instantiate bean cl
    ass [com.models.CustomerBean$CustomerBeanValidator]: No default constructo
    r found; nested exception is java.lang.NoSuchMethodException: com.models.C
    ustomerBean$CustomerBeanValidator.<init>()
    Caused by: org.springframework.beans.BeanInstantiationException: Could not insta
    ntiate bean class [com.models.CustomerBean$CustomerBeanValidator]: No defa
    ult constructor found; nested exception is java.lang.NoSuchMethodException: com.
    models.CustomerBean$CustomerBeanValidator.<init>()
    Caused by: java.lang.NoSuchMethodException: com.models.CustomerBean$Custom
    erBeanValidator.<init>()
            at java.lang.Class.getConstructor0(Class.java:2647)
            at java.lang.Class.getDeclaredConstructor(Class.java:1953)
            at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:6
    0)
            at org.springframework.beans.factory.support.SimpleInstantiationStrategy
    .instantiate(SimpleInstantiationStrategy.java:45)
            at org.springframework.beans.factory.support.AbstractAutowireCapableBean
    Factory.instantiateBean(AbstractAutowireCapableBeanFactory.java:701)
            at org.springframework.beans.factory.support.AbstractAutowireCapableBean
    Factory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:687)
            at org.springframework.beans.factory.support.AbstractAutowireCapableBean
    Factory.createBean(AbstractAutowireCapableBeanFactory.java:388)
            at org.springframework.beans.factory.support.AbstractBeanFactory$1.getOb
    ject(AbstractBeanFactory.java:250)
            at org.springframework.beans.factory.support.DefaultSingletonBeanRegistr
    y.getSingleton(DefaultSingletonBeanRegistry.java:141)
            at org.springframework.beans.factory.support.AbstractBeanFactory.getBean
    (AbstractBeanFactory.java:247)
            at org.springframework.beans.factory.support.AbstractBeanFactory.getBean
    (AbstractBeanFactory.java:161)
            at org.springframework.beans.factory.support.BeanDefinitionValueResolver
    .resolveReference(BeanDefinitionValueResolver.java:245)
            at org.springframework.beans.factory.support.BeanDefinitionValueResolver
    .resolveValueIfNecessary(BeanDefinitionValueResolver.java:124)
            at org.springframework.beans.factory.support.AbstractAutowireCapableBean
    Factory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1019)
            at org.springframework.beans.factory.support.AbstractAutowireCapableBean
    Factory.populateBean(AbstractAutowireCapableBeanFactory.java:809)
            at org.springframework.beans.factory.support.AbstractAutowireCapableBean
    Factory.createBean(AbstractAutowireCapableBeanFactory.java:425)
            at org.springframework.beans.factory.support.AbstractBeanFactory$1.getOb
    ject(AbstractBeanFactory.java:250)
            at org.springframework.beans.factory.support.DefaultSingletonBeanRegistr
    y.getSingleton(DefaultSingletonBeanRegistry.java:141)
            at org.springframework.beans.factory.support.AbstractBeanFactory.getBean
    (AbstractBeanFactory.java:247)
            at org.springframework.beans.factory.support.AbstractBeanFactory.getBean
    (AbstractBeanFactory.java:161)
            at org.springframework.beans.factory.support.DefaultListableBeanFactory.
    preInstantiateSingletons(DefaultListableBeanFactory.java:273)
            at org.springframework.context.support.AbstractApplicationContext.refres
    h(AbstractApplicationContext.java:346)
            at org.springframework.web.context.support.AbstractRefreshableWebApplica
    tionContext.refresh(AbstractRefreshableWebApplicationContext.java:156)
            at org.springframework.web.servlet.FrameworkServlet.createWebApplication
    Context(FrameworkServlet.java:308)
            at org.springframework.web.servlet.FrameworkServlet.initWebApplicationCo
    ntext(FrameworkServlet.java:252)
            at org.springframework.web.servlet.FrameworkServlet.initServletBean(Fram
    eworkServlet.java:221)
            at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.
    java:115)
            at javax.servlet.GenericServlet.init(GenericServlet.java:212)

    The code snippet from my app-servlet.xml is as follows :

    Code:
    <bean id="customerFormController"
                     class="com.controllers.CustomerFormController">
                     <property name="formView">
                            <value>client.htm</value>
                     </property>
                     <property name="successView">
                            <value>client.htm</value>
                     </property>
                      <property name="commandName" value="customerBean" />
                      <property name="commandClass">
                            <ref bean="customerBean" />
                      </property>
                      <property name="validator">
                            <ref bean="customerFormValidator" />
                      </property>
                      <property name="validateOnBinding">
                            <value>true</value>
                      </property>
    
                      <property name="pageCaption">
                            <value>Clients</value>
                      </property>
            </bean>
            
            <bean id="customerBean" class="com.models.CustomerBean" />
            <bean id="customerFormValidator" class="com.models.CustomerBean$CustomerBeanValidator" />


    My bean code snippet is as follows:

    Code:
    public class CustomerBean 
    {
        private String customerName;
        private String companyName;
    
        public void setCustomerName(String customerName) {
              this.customerName = customerName;
        }
    
        public String getCustomerName() {
            return customerName;
        }
    
        public void setCompanyName(String companyName) {
            this.companyName = companyName;
        }
    
        public String getCompanyName() {
            return companyName;
        }
    
       /**
         *  Validates the customer's details submitted.
         *
         */
        protected class CustomerBeanValidator implements Validator {
    
                public CustomerBeanValidator() {
                }
                /**
                 * Returns true if this validator can validate instances of supplied clazz,
                 * else false.
                 *
                 *@param clazz : the class that this Validator is being asked to validate
                 */
                public boolean supports(Class clazz) {
                    return CustomerBean.class.isAssignableFrom(clazz);
                }
    
                /**
                 * Validates the supplied "target" object, which must be of a Class for which the 
                 * supports(Class) method typically has(or would) return true.
                 * The supplied "errors" instance can be used to report ant resulting validation errors.
                 *
                 * @param target : the object that is to be validated(can be "null")
                 * @param errors : contextual state about the  validation process(never "null")
                 */
                public void validate(Object target, Errors errors) {
                        ValidationUtils.rejectIfEmptyOrWhitespace(errors,"customerName","required","Field is required");
                        ValidationUtils.rejectIfEmptyOrWhitespace(errors,"companyName","required","Field is required");
                }
        }
    }


    Can anybody please let me know where i have gone wrong??

    Thanks.
    Last edited by j.gohel; Sep 8th, 2007, 05:57 PM.

  • #2
    It's giving the error "No default constructor found". I'm guessing that's because your inner class is protected and not public. Just put it in a separate file and make it public. You're working with java and spring; just get used to having billions of files.

    Comment


    • #3
      Hi lumpynose,
      Thanks for the reply.

      As per your suggestion of making a separate java file for my validator implemenation, i had already implemented the code that way and it is working.

      But what i am trying is that the bean and its validation logic both remain together.Hence defined the Validator implementation as Inner class.

      Also i tried the option of declaring the inner class's constructor as public.But the same exception was persisting as mentioned in my first post.

      I debugged the application and found out that, in the following method of java.lang.Class, the exception is occuring.

      Code:
      private Constructor[] privateGetDeclaredConstructors(boolean publicOnly) {
              checkInitted();
              Constructor[] res = null;
              if (useCaches) {
                  if (publicOnly) {
                      if (publicConstructors != null) {
                          res = (Constructor[]) publicConstructors.get();
                      }
                  } else {
                      if (declaredConstructors != null) {
                          res = (Constructor[]) declaredConstructors.get();
                      }
                  }
                  if (res != null) return res;
              }
              // No cached value available; request value from VM
              if (isInterface()) {
                  res = new Constructor[0];
              } else {
                  res = getDeclaredConstructors0(publicOnly);
              }
              if (useCaches) {
                  if (publicOnly) {
                      publicConstructors = new SoftReference(res);
                  } else {
                      declaredConstructors = new SoftReference(res);
                  }
              }
              return res;
          }

      The control goes through the the lines marked in BOLD.The res variable's value is coming as null.The method getDeclaredConstructors0(publicOnly) is returning null.

      I tried to look into what is there in this method.But its just declared as

      Code:
      private native Constructor[] getDeclaredConstructors0(boolean publicOnly);
      I am not able to get what is happening.Please help me out.

      Just put it in a separate file and make it public. You're working with java and spring; just get used to having billions of files.
      .

      In the end as per your above comment, is it that we cannot use inner classes when using java and spring ???

      Thanks,
      Jignesh

      Thanks.

      Comment


      • #4
        The reason for your error is not a protected/public thing (at least as far as I know Spring can access protected methods, constructors, classes) but a static/non-static thing as also the move to an extra file clearly shows. It's a plain Java issue and has nothing to do with Spring. You can't instantiate the inner bean CustomerBeanValidator without having an instance of CustomerBean. That's also why it is complaining about "no default constructor found" since it is technically something like new CustomerBeanValidator(customerBean). You can try it out on the Java level with new CustomerBeanValidator() when you are not in an instance of CustomerBean (but in a static method of it or a unrelated class). The compiler will complain.

        Code:
        public static void main(String[] args) {
            CustomerBeanValidator validator = new CustomerBeanValidator(); // compiler error
            CustomerBeanValidator validator = new CustomerBean.CustomerBeanValidator(); // still compiler error
            CustomerBeanValidator validator = new CustomerBean().new CustomerBeanValidator(); //will work
        }
        The longer the speech, the less thought: make your inner bean a nested bean by using the modifier static and it will work.

        Joerg
        Last edited by Jörg Heinicke; Sep 9th, 2007, 11:37 AM.

        Comment


        • #5
          Your setup was completely correct as fas as I could see it. You only need to change the line

          Code:
          protected class CustomerBeanValidator implements Validator
          into

          Code:
          protected static class CustomerBeanValidator implements Validator
          Joerg
          Last edited by Jörg Heinicke; Sep 9th, 2007, 12:10 PM. Reason: The post this answer refers to was deleted while I was writing the answer :)

          Comment


          • #6
            Originally posted by j.gohel View Post
            ... In the end as per your above comment, is it that we cannot use inner classes when using java and spring ??? ...
            Sorry, Joerg obviously understands these things better than I do. I get frustrated with all of the classes I have to create to do the simplest stuff.

            Comment


            • #7
              Spring + Logging using AOP

              Hi,
              I am facing a problem while using the AOP (proxy factory bean usage) for logging mechanism...
              i am new to string to not well versed with the nitty grity...

              my Application context looks as below...
              <?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="contentService" class="com.toro.service.dctm.content.ContentServic eImpl">
              <property name="contentDao" ref="contentDAO" />
              <property name="authenticationDao" ref="authenticationDAO" />
              <property name="zipFilePath" value="C:\\ContentZip" />
              </bean>

              <bean id="authenticationDAO" class="com.toro.service.dctm.authentication.dao.Au thenticationDAOImpl"></bean>
              <!-- Configure spring to give a hook to axis2 without a ServletContext -->
              <bean id="applicationContext" class="org.apache.axis2.extensions.spring.receiver s.ApplicationContextHolder" ></bean>

              <bean id="loggingInterceptor" class="com.toro.service.dctm.util.LoggingIntercept or"/>
              <!-- <bean id="contentDAO" class="com.toro.service.dctm.content.dao.ContentDa oImpl" />-->


              <bean id="contentDAO" class="org.springframework.aop.framework.ProxyFact oryBean" >
              <property name="proxyTargetClass" value="true"/>
              <property name="proxyInterfaces" >
              <value>com.toro.service.dctm.content.dao.ContentDa o</value>
              </property>
              <property name="target">
              <bean class="com.toro.service.dctm.content.dao.ContentDa oImpl" />
              </property>
              <property name="interceptorNames">
              <list>
              <value>loggingInterceptor</value>
              </list>
              </property>
              </bean>

              </beans>


              the Logger class (oggingInterceptor bean) is as below

              package com.toro.service.dctm.util;

              import java.lang.reflect.Method;
              import org.apache.commons.logging.Log;
              import org.apache.commons.logging.LogFactory;
              import org.springframework.aop.AfterReturningAdvice;
              import org.springframework.aop.MethodBeforeAdvice;
              import org.springframework.aop.ThrowsAdvice;

              public class LoggingInterceptor implements MethodBeforeAdvice, AfterReturningAdvice, ThrowsAdvice{
              private static Log log = null;
              public LoggingInterceptor(){
              }

              public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable {
              log = LogFactory.getLog(arg2.getClass());
              log.debug("Beginning method: "+arg0.getName());
              System.out.println("In The LoggingInterceptor Before Method...");
              }

              public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws Throwable {
              log = LogFactory.getLog(arg3.getClass());
              log.info("Ending method: "+arg1.getName());
              System.out.println("In The LoggingInterceptor afterReturningx Method...");
              }

              public void afterThrowing(Method m, Object[] args, Object target, Throwable ex){
              log = LogFactory.getLog(target.getClass());
              log.info("Exception in method: "+m.getName()+" Exception is: "+ex.getMessage());
              }
              }


              now i am facing a problem while instantiating the contentService class as this has got the refrence to the contentDAO which is supposed to be aproxy...
              the error message i am getting is as below..

              I am totally lost as what need to be done to fix this issue...
              Please let me know...


              org.springframework.beans.factory.BeanCreationExce ption: Error creating bean with name 'contentService' defined in class path resource [contentServiceContext.xml]: Cannot resolve reference to bean 'contentDAO' while setting bean property 'contentDao'; nested exception is org.springframework.beans.factory.BeanCreationExce ption: Error creating bean with name 'contentDAO' defined in class path resource [contentServiceContext.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationExcepti on: Could not instantiate bean class [org.springframework.aop.framework.ProxyFactoryBean]: Constructor threw exception; nested exception is java.lang.NoSuchMethodError: org.springframework.util.ClassUtils.isPresent(Ljav a/lang/StringZ
              org.springframework.beans.factory.BeanCreationExce ption: Error creating bean with name 'contentDAO' defined in class path resource [contentServiceContext.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationExcepti on: Could not instantiate bean class [org.springframework.aop.framework.ProxyFactoryBean]: Constructor threw exception; nested exception is java.lang.NoSuchMethodError: org.springframework.util.ClassUtils.isPresent(Ljav a/lang/StringZ
              org.springframework.beans.BeanInstantiationExcepti on: Could not instantiate bean class [org.springframework.aop.framework.ProxyFactoryBean]: Constructor threw exception; nested exception is java.lang.NoSuchMethodError: org.springframework.util.ClassUtils.isPresent(Ljav a/lang/StringZ
              java.lang.NoSuchMethodError: org.springframework.util.ClassUtils.isPresent(Ljav a/lang/StringZ
              at

              Comment


              • #8
                First when posting code please use the [ code][/code ] tags!!! It makes your post readable, which it really isn't right now.

                Regarding your error you seem to have a version/classloading issue. Make sure you have all the right versions in your classpath and not 2 versions of the spring.jar.

                Comment


                • #9
                  spring jars..

                  i have following jars for string in place..
                  spring.jar
                  spring-beans.jar
                  spring-context.jar
                  spring-core.jar
                  spring-dao.jar
                  spring-hibernate.jar
                  spring-jdbc.jar
                  spring-mock.jar
                  spring-orm.jar
                  spring-web.jar
                  spring-webmvc.jar
                  and one for axis..
                  axis2-spring-1.1.1.jar
                  and the rest of the jars...
                  so i dont think there is problem of version conflict...

                  Comment


                  • #10
                    I would delete spring*.jar and copy a fresh copy from your Spring download/distribution. The problem is most definitely caused by a version mismatch somewhere. Also, if you are running in an app server, make sure that spring*.jar lives nowhere else in the app server (for e.g. server/lib, common/lib, etc).

                    Comment


                    • #11
                      so i dont think there is problem of version conflict...
                      Well I really think there is... Why?

                      spring.jar already contains everything which is in spring-beans.jar, spring-context.jar etc... So either remove spring-*.jar or remove the spring.jar.

                      Comment


                      • #12
                        Originally posted by mdeinum View Post
                        First when posting code please use the [ code][/code ] tags!!! It makes your post readable, which it really isn't right now.
                        Second please don't hijack threads with a completely different topic. Nobody will be able to find the stuff they are looking for ...

                        Joerg

                        Comment


                        • #13
                          Access Objects in validation.xml

                          Hi,

                          How do i access an object in validation.xml. I am using Bean Validation Framework.

                          My class:
                          Code:
                          public class Employee {
                          	
                          	private String firstName;
                          	private String lastName;
                          	private Department department; 
                          //with getters and setters
                          }
                          My employee-validation.xml

                          Code:
                          <?xml version="1.0" encoding="ISO-8859-1"?>
                          <validation xmlns="http://www.springmodules.org/validation/bean" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://localhost:8080/BVF http://localhost:8080/BVF/validation.xsd">
                          	
                          	<class name="Employee">
                          		<validator class="EmployeeValidator"/>
                          		
                          		<property name="firstName">
                          			<not-blank message="FirstName cannot be left blank"/>
                          			<length min="5" max="20" message="First Name Length cannot be less than 5 or more than 20"/>
                          		</property>
                          		
                          		<property name="lastName">
                          			<not-blank message="LastName cannot be left balnk"/>
                          			<length min="5" max="20" message="Last Name Length cannot be less than 5 or more than 20"/>
                          		</property>
                          		
                          		<property name="department.name">
                          	            <not-blank message="Name cannot be blank"/>
                          	            <length min="5" max="20" message="Name Length cannot be less than 5 or more than 20"/>
                                 		</property>
                           
                                 		<property name="department.pinCode">
                          	     	   <not-blank message="Pin Code cannot be left blank"/> 
                          		        <regexp expression="^[A-Z\d{1}]\d{4}[\s\-]*\d*$" message="PinCode is invalid"/>       	
                          		        <length min="5" max="10" message="Pincode length should be between 5 and 10"/>
                                  	
                                 		</property>
                          	
                          	</class>
                          	
                          </validation>
                          can someone tell me how i can access the elements of department object. Code in bold doesnt seem to be working.

                          Comment


                          • #14
                            Please start a new thread! Or to quote myself from just immediately before your post (I wonder if you posted by intention and just want to annoy us ):

                            Originally posted by Jörg Heinicke View Post
                            Second please don't hijack threads with a completely different topic.
                            Joerg

                            Comment


                            • #15
                              I am so sorry... i didnt mean to annoy you

                              Comment

                              Working...
                              X