Spring容器启动配置
什么时候spring容器启动?其实就是程序中执行加载 web.xml配置文件的时候。
Spring可以通过(Servlet) org.springframework.web.context.ContextLoaderServlet 和Listener( org.springframework.web.context.ContextLoaderListener )两个类作为Spring启动的入口。
- 1.应用程序下加载
ApplicationContext context = new FileSystemXmlApplicationContext("WebRoot/WEB-INF/applicationContext.xml");
applicationContext.xml内容如下:
<! DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd" >
< beans >
<!-- dataSource config -->
< bean id ="dataSource" class ="org.apache.commons.dbcp.BasicDataSource" destroy-method ="close" >
< property name ="driverClassName" value ="com.mysql.jdbc.Driver" />
< property name ="url" value ="jdbc:mysql://localhost:3306/game" />
< property name ="username" value ="root" />
< property name ="password" value ="root" />
</ bean >
<!-- SessionFactory -->
< bean id ="sessionFactory"
class ="org.springframework.orm.hibernate3.LocalSessionFactoryBean" >
< property name ="dataSource" >
< ref bean ="dataSource" />
</ property >
< property name ="configLocation" >
< value > classpath:com\sterning\bean\hibernate\hibernate.cfg.xml </ value >
</ property >
</ bean >
<!-- TransactionManager 不过这里暂时没注入 -->
< bean id ="transactionManager"
class ="org.springframework.orm.hibernate3.HibernateTransactionManager" >
< property name ="sessionFactory" >
< ref local ="sessionFactory" />
</ property >
</ bean >
<!-- DAO -->
< bean id ="booksDao" class ="com.sterning.books.dao.hibernate.BooksMapDao" >
< property name ="sessionFactory" >
< ref bean ="sessionFactory" />
</ property >
</ bean >
<!-- Services -->
< bean id ="booksService" class ="com.sterning.books.services.BooksService" >
< property name ="booksDao" >
< ref bean ="booksDao" />
</ property >
</ bean >
< bean id ="pagerService" class ="com.sterning.commons.PagerService" />
<!-- view -->
< bean id ="bookAction" class ="com.sterning.books.web.actions.BooksAction" singleton ="false" >
< property name ="booksService" >
< ref bean ="booksService" />
</ property >
< property name ="pagerService" >
< ref bean ="pagerService" />
</ property >
</ bean >
</ beans >
- 2.web模式下加载
web.xml:
<context-param>
<param-name>
log4jConfigLocation
</param-name>
<param-value>/WEB-INF/classes/log4j.properties</param-value>
</context-param>
<!-- ContextConfigLocation -->
<context-param>
<param-name>
contextConfigLocation
</param-name>
<param-value>/WEB-INF/spring-context/applicationContext.xml</param-value>
</context-param>
<!-- Listener contextConfigLocation -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!-- Listener log4jConfigLocation -->
<listener>
<listener-class>
org.springframework.web.util.Log4jConfigListener
</listener-class>
</listener>