[英]What's the intended use of `servlet-context.xml`, `root-context.xml` and `web.xml`?
[英]How do I load servlet-context.xml automatically?
我是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
文件最簡潔,最簡單的方法是什么?
你可以用uselistener來加載上下文...
<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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.