【发布时间】:2023-03-23 22:20:01
【问题描述】:
我想在我的 Spring MVC Web 应用程序(打包为 WAR)中加载一些带有 @Service 注释的 Spring 框架 bean,来自外部 jar,它负责访问数据库和 位于/WEB-INF/lib 下的类路径中。如果可能,最好使用 @Autowired 注释自动加载它们。
我已经成功地遵循了这个link1中的解决方案:
this.ctx = new ClassPathXmlApplicationContext("services-context.xml");
this.myAService = ctx.getBean("myAService");
但是,此解决方案使用 Spring API 函数 getBean,这被认为是一种不好的做法(请参阅 link2)。
我也尝试过加载外部 jar 的 applicationContext 的另外两件事,但没有运气:
-
WAR 的 appContext.xml:
<import resource="classpath*:/WEB-INF/lib/pathToExternalJar/applicationContext.xml"> -
WAR 的 web xml -> 加载 jar 的 appContext,如此处所述 (link3)。 (例如 *applicationContext.xml):
<context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:localSpringContext.xml classpath:*applicationContext.xml </param-value> </context-param>
正确加载这些 bean 的最佳方法是什么?应该如何完成?
【问题讨论】:
标签: spring-mvc jar dependency-injection war autowired