Is a default constructor required in Spring injection?

I am trying to insert a constructor that takes some arguments. After compiling, Spring complains that it could not find the default constructor (I did not define it) and throws a BeanInstatiationException and a NoSuchMethodException.

After defining the default constructor, exceptions are no longer displayed, however, my object is never initialized by the argument constructor, only by default are called. In this case, is Spring the default constructor required? And if so, how can I get it to use the argument constructor instead of the standard?

Here's how I spend it all:

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>() 
+6
source share
3 answers

Spring only “requires” a default constructor if you plan on creating it without any arguments.

for example, if your class looks like this:

 public class MyClass { private String something; public MyClass(String something) { this.something = something; } public void setSomething(String something) { this.something = something; } } 

and you install it in Spring as follows:

 <bean id="myClass" class="foo.bar.MyClass"> <property name="something" value="hello"/> </bean> 

You will get an error message. the reason is that Spring creates an instance of the new MyClass() class, then tries to set setSomething(..) .

so instead, Spring xml should look like this:

 <bean id="myClass" class="foo.bar.MyClass"> <constructor-arg value="hello"/> </bean> 

so look at com.client.Module and see how it is configured in your Spring xml

+7
source

Most likely you are using component scanning, and since you are defining the @Component annotation for the class module, it is trying to instantiate a bean. You do not need the @Component annotation if you use XML to define a bean.

+4
source

Just facing the same problem, I think so far you may have solved the problem.
Below you can change the bean configuration to

 <bean id="module" class="com.client.Module"> <constructor-arg value="Text"/> </bean> 
+2
source

Source: https://habr.com/ru/post/951084/


All Articles