Page 1 of 2 12 LastLast
Results 1 to 10 of 18

Thread: Context initialization failing due to inner class usage

  1. #1

    Default 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 at 04:57 PM.

  2. #2
    Join Date
    May 2005
    Location
    California, US
    Posts
    735

    Default

    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.

  3. #3

    Default

    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.

  4. #4
    Join Date
    Nov 2005
    Location
    Reutlingen, Germany
    Posts
    2,098

    Default

    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 at 10:37 AM.
    This post can contain insufficient information.

  5. #5
    Join Date
    Nov 2005
    Location
    Reutlingen, Germany
    Posts
    2,098

    Default

    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 at 11:10 AM. Reason: The post this answer refers to was deleted while I was writing the answer :)
    This post can contain insufficient information.

  6. #6
    Join Date
    May 2005
    Location
    California, US
    Posts
    735

    Default

    Quote 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.

  7. #7
    Join Date
    Sep 2007
    Posts
    15

    Default 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

  8. #8
    Join Date
    Jun 2006
    Location
    The Netherlands
    Posts
    13,632

    Default

    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.
    Marten Deinum
    Java Consultant / Pragmatist / Open Source Enthousiast / Author


    Pro Spring MVC: With Web Flow
    Conspect

    Have you read the reference guide.
    Use the [ code ] tags, young padawan

  9. #9
    Join Date
    Sep 2007
    Posts
    15

    Default 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...

  10. #10
    Join Date
    Sep 2004
    Location
    Manchester, NH
    Posts
    1,236

    Default

    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).
    Peter Mularien | Blog
    Author, Spring Security 3 (Book) - Packt Publishing, Available in print and eBook form
    SCJP 5, Oracle DBA
    Any postings are my own opinion, and should not be attributed to my employer or clients.


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •