我正在尝试运行以下类。
package com.example.demo;
import org.apache.catalina.core.ApplicationContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
var factory = new AnnotationConfigApplicationContext(AppConfig.class);
test tst = factory.getBean(test.class);
tst.getDummy().test();
SpringApplication.run(DemoApplication.class, args);
}
}
应用程序配置类:
package com.example.demo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public test gettest(){
return new test();
}
//
@Bean
public test2 gettest2(){
return new test2();
}
}
第一个测试类:
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
@Component
public class test{
@Autowired
test2 dummy;
public void setDummy(test2 dummy) {
this.dummy = dummy;
}
public test2 getDummy() {
return dummy;
}
void test(){
System.out.println("test");
}
}
第二个测试类:
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
@Component
public class test2{
public test2(){
}
void test(){
System.out.println("test2");
}
}
我在运行时遇到了这个错误
Field dummy in com.example.demo.test required a single bean, but 2 were found:
- test2: defined in file [/Users/biliuta/IdeaProjects/demo/build/classes/java/main/com/example/demo/test2.class]
- gettest2: defined by method 'gettest2' in class path resource [com/example/demo/AppConfig.class]
如果我在 AppConfig 中注释掉 public test2 gettest2() bean,就会出现以下错误:
Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'gettest': Unsatisfied dependency expressed through field 'dummy'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.demo.test2' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
为什么在第一个例子中可以找到test2 bean,但是当我从AppConfig中注释掉它时,就无法再找到它了(在第一个错误消息中,你可以清楚地看到test2已经被找到了)?@Configure注解是否是将bean添加到上下文中的必要条件?