我有一个爱好项目,我想将其迁移到 Spring。
作为示例,我有以下类(class):
public class OtherBean {
public void printMessage() {
System.out.println("Message from OtherBean");
}
}
public class InjectInMe {
@Inject OtherBean otherBean;
public void callMethodInOtherBean() {
otherBean.printMessage();
}
}
但是,当我阅读文档时,我必须使用@Component(或其他类似的注释)之类的注释来注释由 Spring 管理的所有类。
使用以下代码运行它:
public class SpringTest {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.refresh();
InjectInMe bean = context.getBean(InjectInMe.class);
bean.callMethodInOtherBean();
}
}
给我错误:
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [somepackage.InjectInMe] 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:968)
at somepackage.SpringTest.main(SpringTest.java:10)
我的问题是:有没有办法让 Spring 管理我要求 ApplicationContext 实例化的任何类而我不必在带注释的配置(或 XML 配置)中注册它们?
在 Guice 中我可以直接注入(inject)类
public class GuiceTest {
static public class GuiceConfig extends AbstractModule {
@Override
protected void configure() {}
}
public static void main(String[] args) {
Injector injector = Guice.createInjector(new GuiceConfig());
InjectInMe bean = injector.getInstance(InjectInMe.class);
bean.callMethodInOtherBean();
}
}
给我输出:
Message from OtherBean
有没有办法让 Spring 像 Guice 一样工作?就像让 Spring 注入(inject)我的 bean 一样,而无需我必须注册或扫描包中使用 @Component 类注释进行注释的类?
Spring高手有办法解决这个问题吗?
最佳答案
My question is: is there a way to make Spring manage any class I ask the ApplicationContext to instantiate without me having to register them in an Annotated Config (or XML config)?
不,这是不可能的。这根本不是 Spring 的设计方式。您必须隐式(例如扫描 + 注释)或显式(例如 XML bean 定义)注册您的 bean。
你至少可以做的是:
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(OtherBean.class);
context.register(InjectInMe.class);
context.refresh();
关于java - 让 Spring 的 IoC 容器以零配置实例化 beans(如 Google Guice 的行为),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27068178/