SpringMVCでは、コントローラーは注釈@Resourceを直接使用してサービスビジネスロジックレイヤーを呼び出すことができますが、通常のクラスまたはツールクラスがサービスインターフェイスを呼び出す必要がある場合はどうすればよいですか?
次に、2つのソリューションを提供します
1. Spring構成ファイルをリロードして、コンテキストBeanをインスタンス化します
ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext-common.xml");
StudentService studentService = (StudentService)appContext.getBean("studentService");
ClassPathXmlApplicationContextをエントリポイントとして使用して、CLASSPATHの下にSpring構成ファイルをロードし、すべてのBeanインスタンスのロードを完了して、Beanインスタンスを取得します。
2. ApplicationContextAwareインターフェイスを実装します(推奨)
ApplicationContextAwareインターフェイスを介して、インスタンス化されたBeanを既存のSpringコンテキストから取得できます。
(1)ApplicationContextAwareインターフェイスを実装するためのツールクラスSpringContextUtilを作成します
@Component
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext appCtx;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
appCtx = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return appCtx;
}
// 添加getBean()方法,凭id获取容器管理的Bean
public static Object getBean(String beanName) {
return appCtx.getBean(beanName);
}
}
(2)ツールクラスSpringContextUtilをSpringコンテナに挿入します
<bean id="springContextUtil" class="com.cn.unit.spring.SpringContextUtil"/>
(3)プロジェクトweb.xmlでSpringコンテナをロードするリスナーを構成します
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
(4)そうすれば、春のコンテナに豆を喜んで入れることができます
UserServiceImpl userService = (UserServiceImpl) SpringContextUtil.getBean("userService");
userService.insertUser(user);
誰かにバラの手を与えて香りを残してください、それがあなたを助けるなら、来て
点个赞
ください!