私はSpringチュートリアルから始めていて、この簡単なコードを試していました.
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(HelloWorldConfig.class);
ctx.register(HelloWorldConfig1.class);
ctx.refresh();
HelloWorld helloWorld = ctx.getBean(HelloWorld.class);
helloWorld.setMessage("Hello World!");
helloWorld.getMessage();
HelloWorld1 helloWorld1 = ctx.getBean(HelloWorld1.class);
helloWorld1.setMessage("Hello World!");
helloWorld1.getMessage();
これは以下の例外をスローしています。
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.tutorialspoint.HelloWorld] is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:295)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1125)
at com.tutorialspoint.MainApp.main(MainApp.java:13)
ただし、構成を 1 つだけ登録してそこから Bean を使用すると、問題なく動作します。したがって、HelloWorld/HelloWorldConfig または HelloWorld/HelloWorldConfig1 を個別に使用すると正常に動作しますが、両方を一緒に登録した場合にのみ、このエラーが発生します。
以下の他のクラス、
package com.tutorialspoint;
import org.springframework.context.annotation.*;
@Configuration
public class HelloWorldConfig {
@Bean
public HelloWorld helloWorld(){
return new HelloWorld();
}
}
と
package com.tutorialspoint;
import org.springframework.context.annotation.*;
@Configuration
public class HelloWorldConfig1 {
@Bean
public HelloWorld1 helloWorld(){
return new HelloWorld1();
}
}
と
package com.tutorialspoint;
public class HelloWorld {
private String message;
public void setMessage(String message){
this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
}
}
と
package com.tutorialspoint;
public class HelloWorld1 {
private String message;
public void setMessage(String message){
this.message = message;
}
public void getMessage(){
System.out.println("Your Message 1: " + message);
}
}