我有一個愛好項目,我想遷移到Spring。讓Spring的IoC容器實例化零配置bean(如Google Guice的行爲)
舉個例子,我有以下類別:
public class OtherBean {
public void printMessage() {
System.out.println("Message from OtherBean");
}
}
public class InjectInMe {
@Inject OtherBean otherBean;
public void callMethodInOtherBean() {
otherBean.printMessage();
}
}
但是因爲我讀的文件,我必須註解要由Spring與像@Component註釋管理的所有類別(或其他人是相似的) 。
用下面的代碼運行它:
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)
我的問題是:有沒有一種方法,使春季管理任何類我問的ApplicationContext實例沒有我必須註冊他們在一個註釋的配置(或XML配置)?
在吉斯我可以注入類
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的AnnotationConfigApplicationContext,並且發現沒有簡單的方法來添加這種類Guice行爲。我暫時堅持Guice,因爲我不會註冊所有**我的課程。我希望春天在未來給我們一個選擇。 – 2014-11-21 21:35:37