java - 如何自动加载 servlet-context.xml?

标签 java xml spring spring-mvc servlets

我是 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/

相关文章:

java - Google App Engine 上的 GSON 抛出安全异常

xml - XSLT 中的日期时间分组问题

java - 带有 PropertyPlaceholderConfigurer bean 的 Spring @Configuration 文件无法解析 @Value 注释

spring - 无法使用 Spring Security 评估表达式

java bean注入(inject)

java - 使用依赖项 maven 构建 jar

java - 可以写成两个平方和的数字

java - 在同一个窗口java中显示许多文本

xml - XSLT 意外的重复文本

C# Xelement 到字符串 - 将标签转换为 &lt 和 &gt