Spring Multiple Constructor Injection ohne @autowryingJava

Java-Forum
Guest
 Spring Multiple Constructor Injection ohne @autowrying

Post by Guest »

Ich versuche, Konstruktorinjektion zu verwenden. Ich verstehe, dass bei der Suche nach mehreren Konstruktoren versucht wird, die mit der größten Anzahl von Argumenten auszuwählen, bei denen die Typen mit auf den Frühling verwalteten Bohnen übereinstimmen. In diesem Beispiel schlägt es jedoch fehl. Normalerweise sollte es den zweiten Konstruktor nennen.

Code: Select all

package autowiring;

import org.springframework.stereotype.Component;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

@Configuration
@ComponentScan
class config{

}

@Component
public class comp1{
Foo ab;
Boo bo;
public  comp1(Foo ab,String a,X d){
System.out.println("constructor 1 called");

this.ab=ab;
}
public comp1(Foo ab,Boo bo){
System.out.println("constructor 2 called");
this.ab=ab;
this.bo=bo;
}
public static void main(){
var ctx=new AnnotationConfigApplicationContext(config.class);
}
}

@Component
class Foo{
String name="Foo";
}

@Component
class Boo{
String name="Bar";
}

class X{

}
< /code>
Die Ausgabe: < /p>
amdi@debian:~/Documents/learn/java2/test$ java -jar target/my*.jar
Feb 18, 2025 6:39:04 AM org.springframework.context.support.AbstractApplicationContext refresh
WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'comp1' defined in URL [jar:file:/home/lmhamdi/Documents/learn/java2/test/target/my-app-1.0.0.jar!/autowiring/comp1.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [autowiring.comp1]: No default constructor found; nested exception is java.lang.NoSuchMethodException: autowiring.comp1.()
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'comp1' defined in URL [jar:file:/home/lmhamdi/Documents/learn/java2/test/target/my-app-1.0.0.jar!/autowiring/comp1.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [autowiring.comp1]: No default constructor found; nested exception is java.lang.NoSuchMethodException: autowiring.comp1.()
at org.springframe

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post