如何修复以下示例,以便通知Spring 应用程序上下文在哪里可以找到Application
其构造函数带有注释的类@Inject
,但不引入带有ApplicationConfiguration
注释的 bean 方法@Bean
返回类的实例Application
?
public class Application {
private final A a;
@Inject
public Application(A a) {
this.a = a;
}
public A getA() {
return a;
}
}
@Configuration
public class ApplicationConfiguration {
@Bean
public A getA() {
return new A();
}
}
public class A {
}
public class Start {
public static void main(String[] arguments) {
final ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfiguration.class);
final Application application = context.getBean(Application.class);
application.getA();
}
}
您可以在GitHub 上的AtInject项目中查看源代码。
当我运行类Start
时,Spring 抱怨它找不到类Application
:
May 27, 2016 4:49:55 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@7eda2dbb: startup date [Fri May 27 16:49:55 EDT 2016]; root of context hierarchy
May 27, 2016 4:49:55 PM org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor <init>
INFO: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.opessoftware.atinject.application.Application] is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:371)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:331)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:975)
at com.opessoftware.atinject.start.Start.main(Start.java:11)