Spring に移行したい趣味のプロジェクトがあります。
例として、次のクラスがあります。
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)
私の質問は、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のように動作させることはできますか? @Component のようなアノテーションが付けられたクラスのパッケージを登録またはスキャンすることなく、Spring に Bean を注入させるようにするにはどうすればよいでしょうか。
この問題を解決する方法を持っている春の達人はいますか?