Spring 管理のアプリケーション コンテキスト対応のクラスを作成できます。このクラスは、コードのどこからでも静的メソッドを介して Spring Bean を提供します。
@Service
public class SpringBeansProvider implements ApplicationContextAware {
static private ApplicationContext applicationContext;
public static <T> T getBean(String beanName, Class<T> type) {
return applicationContext.getBean(beanName, type);
}
@Override
public void setApplicationContext(ApplicationContext context) {
applicationContext = context;
}
}
コードのどこからでも、 を使用しますSpringBeansProvider.getBean("myBean", MyBean.class)
。はい、これは Bean インジェクションの概念を打ち破り、静的メソッドと非静的メソッドの使用を混同しますが、そのような種類のタスクは常に不公平を引き起こします。