【发布时间】:2016-12-24 17:14:29
【问题描述】:
我是 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 文件的最干净和最简单的方法是什么?
【问题讨论】:
-
“当您使用@Autowired 时这不起作用”是什么意思? autowired 是出现在代码中的注解,与 beans 定义文件无关
标签: java xml spring spring-mvc servlets