spring加载配置文件有三种方式:
1.把applicationContext.xml放到WEB-INF/classes下,spring会进行默认加载。
2.在web.xml中进行配置:
<servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:conf/spring-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>
或者是:
1 2 3 4 5 6 7 |
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:conf/spring-servlet.xml</param-value> </context-param> |
3.代码中动态加载:
ApplicationContext context = new ClassPathXmlApplicationContext("conf/spring-servlet.xml");
工作中遇到新的情况:lz把service和dao打成jar作为组件供其他模块引用,但是dataSource.xml在jar内,不知道能否加载。经过lz的研究,可以通过以下方式:
web项目,在web.xml中添加:
1 2 3 4 |
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:conf/**/dataSource.xml</param-value> </context-param> |
普通项目,在已有的spring配置文件中添加:
1 |
<import resource="classpath*:conf/**/dataSource.xml" /> |