我是 Spring Framework 的新手,目前正在尝试弄清楚如何在应用程序启动时自动加载名为 servlet-context.xml
的文件。该文件包含一个 bean 定义,我想在我的应用程序代码中使用 @Autowired
来使用它。
注意:我知道我可以执行类似以下操作来手动加载 Bean,但是当您使用 @Autowired
时,这不起作用:
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
SomeObjectType x = (SomeObjectType)context.getBean("someObjectType");
我从另一个教程中找到了这个代码示例,该教程讲述了如何加载 servlet-context.xml
,但它是从使用 MVC 模式的 Web 应用程序项目中获取的。我没有使用 MVC 的网络应用程序,所以我认为它不适用于我:
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
我的 servlet-context.xml
文件的内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<beans:bean id="dbDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<beans:property name="jndiName" value="java:comp/env/jdbc/Database"/>
</beans:bean>
</beans:beans>
那么加载 servlet-context.xml
文件最干净、最简单的方法是什么?
最佳答案
您可以使用监听器加载上下文...
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/appServlet/servlet-context.xml
</param-value>
</context-param>
关于java - 如何自动加载 servlet-context.xml?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39006914/