I'm trying to inject a constructor that takes some arguments. After compiling Spring complains it couldn't find a default constructor (I haven't defined it) and throws BeanInstatiationException and NoSuchMethodException.
After defining a default constructor the exceptions don't appear anymore, however my object is never initialized with the argument constructor, only the default one is called. Does Spring really require a default constructor in this case? And if yes, how can I make it use the argument constructor instead of the default one?
This is how I wire everything:
public class Servlet {
@Autowired
private Module module;
(code that uses module...)
}
@Component
public class Module {
public Module(String arg) {}
...
}
Bean configuration:
<beans>
<bean id="module" class="com.client.Module">
<constructor-arg type="java.lang.String" index="0">
<value>Text</value>
</constructor-arg>
</bean>
...
</beans>
Stack trace:
WARNING: Could not get url for /javax/servlet/resources/j2ee_web_services_1_1.xsd
ERROR initWebApplicationContext, Context initialization failed
[tomcat:launch] org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'module' defined in URL [...]: Instantiation of bean failed;
nested exception is org.springframework.beans.BeanInstantiationException: Could not
instantiate bean class [com.client.Module]: No default constructor found; nested
exception is java.lang.NoSuchMethodException: com.client.Module.<init>()
Just faced the same problem, i guess till now you might have solved the problem.
Below is what you could have changed your bean configuration to,
Most probably you are using component-scanning and since you define annotation
@Component
for class Module it tries to instantiate the bean. You do not need@Component
annotation if You are using XML for bean definition.Spring only "requires" a default constructor if you plan on instantiating it without any arguments.
for example, if your class is like this;
and you set it up in Spring like this;
you're going to get an error. the reason is that Spring instantiates your class
new MyClass()
then tries to set callsetSomething(..)
.so instead, the Spring xml should look like this;
so have a look at your
com.client.Module
and see how its configured in your Spring xml