我有一个爱好项目,我想迁移到 Spring。
例如,我有以下类:
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 实例化的任何类在 Annotated Config(或 XML 配置)中注册它们?
在 Guice 中,我可以注入课堂
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 注入我的 bean 一样,我不必注册或扫描带有 @Component 类注释的类的包?
任何 Spring 大师有办法解决这个问题吗?