首先宏观的了解一下Spring 框架
Spring 框架是一个分层架构,由 7 个定义良好的模块组成。Spring 模块构建在核心容器之上,核心容器定义了创建、配置和管理 bean 的方式,如图 1 所示。
组成 Spring 框架的每个模块(或组件)都可以单独存在,或者与其他一个或多个模块联合实现。每个模块的功能如下:
- 核心容器:核心容器提供 Spring 框架的基本功能。核心容器的主要组件是
BeanFactory
,它是工厂模式的实现。BeanFactory
使用控制反转 (IOC) 模式将应用程序的配置和依赖性规范与实际的应用程序代码分开。 - Spring 上下文:Spring 上下文是一个配置文件,向 Spring 框架提供上下文信息。Spring 上下文包括企业服务,例如 JNDI、EJB、电子邮件、国际化、校验和调度功能。
- Spring AOP: 通过配置管理特性,Spring AOP 模块直接将面向方面的编程功能集成到了 Spring 框架中。所以,可以很容易地使 Spring 框架管理的任何对象支持 AOP。Spring AOP 模块为基于 Spring 的应用程序中的对象提供了事务管理服务。通过使用 Spring AOP,不用依赖 EJB 组件,就可以将声明性事务管理集成到应用程序中。
- Spring DAO:JDBC DAO 抽象层提供了有意义的异常层次结构,可用该结构来管理异常处理和不同数据库供应商抛出的错误消息。异常层次结构简化了错误处理,并且极大地降低了需要编写 的异常代码数量(例如打开和关闭连接)。Spring DAO 的面向 JDBC 的异常遵从通用的 DAO 异常层次结构。
- Spring ORM:Spring 框架插入了若干个 ORM 框架,从而提供了 ORM 的对象关系工具,其中包括 JDO、Hibernate 和 iBatis SQL Map。所有这些都遵从 Spring 的通用事务和 DAO 异常层次结构。
- Spring Web 模块:Web 上下文模块建立在应用程序上下文模块之上,为基于 Web 的应用程序提供了上下文。所以,Spring 框架支持与 Jakarta Struts 的集成。Web 模块还简化了处理多部分请求以及将请求参数绑定到域对象的工作。
- Spring MVC 框架:MVC 框架是一个全功能的构建 Web 应用程序的 MVC 实现。通过策略接口,MVC 框架变成为高度可配置的,MVC 容纳了大量视图技术,其中包括 JSP、Velocity、Tiles、iText 和 POI。
Spring 框架的功能可以用在任何 J2EE 服务器中,大多数功能也适用于不受管理的环境。Spring 的核心要点是:支持不绑定到特定 J2EE 服务的可重用业务和数据访问对象。毫无疑问,这样的对象可以在不同 J2EE 环境 (Web 或 EJB)、独立应用程序、测试环境之间重用。
Bean工厂实例的创建方式
1.编程式
(1 )测试beng定义档
:
package
jp.co.oms.web.action.pdf;
import org.apache.commons.collections.Factory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
public class a ... {
public static void main(String[] args) ...{
// Resource rs = new FileSystemResource("/config/applicationContext-ibatis.xml");
//[oms] [INFO ] 2007-12-05 08:43:23 [xml.XmlBeanDefinitionReader.loadBeanDefinitions():293] - Loading XML bean definitions from file [E:configapplicationContext-ibatis.xml]
//Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from file [E:configapplicationContext-ibatis.xml]; nested exception is java.io.FileNotFoundException: configapplicationContext-ibatis.xml (指定されたパスが見つかりません。)
//Caused by: java.io.FileNotFoundException: configapplicationContext-ibatis.xml (指定されたパスが見つかりません。)
Resource rs = new FileSystemResource("config/applicationContext-ibatis.xml");//[oms] [INFO ] 2007-12-05 08:40:18 [xml.XmlBeanDefinitionReader.loadBeanDefinitions():293] - Loading XML bean definitions from file [E:program fileseclipseofomseclipseworkspaceomsconfigapplicationContext-ibatis.xml]
BeanFactory factory = new XmlBeanFactory(rs);
// test aa = (test)factory.getBean("applicationListDao1");
// System.out.println(aa);
// ApplicationContext app = new ClassPathXmlApplicationContext("classpath:config/applicationContext-ibatis.xml");
// ApplicationContext app = new ClassPathXmlApplicationContext("classpath*:config/applicationContext-ibatis.xml");
ApplicationContext app = new ClassPathXmlApplicationContext(new String[]...{"classpath:config/applicationContext-ibatis.xml"});
// ApplicationContext app = new ClassPathXmlApplicationContext(new String[]{"config/applicationContext-ibatis.xml"});
test pp = (test)app.getBean("applicationListDao1");
String[] aa = (String[])app.getBeanDefinitionNames();
System.out.println(aa);
System.out.println(pp.getSqlMapClientTemplate().getSqlMapClient().getDataSource());
System.out.println(app instanceof Factory);
System.out.println(app == factory);
ApplicationContext app1 = new FileSystemXmlApplicationContext("classpath:config/applicationContext-ibatis.xml");
}
}
import org.apache.commons.collections.Factory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
public class a ... {
public static void main(String[] args) ...{
// Resource rs = new FileSystemResource("/config/applicationContext-ibatis.xml");
//[oms] [INFO ] 2007-12-05 08:43:23 [xml.XmlBeanDefinitionReader.loadBeanDefinitions():293] - Loading XML bean definitions from file [E:configapplicationContext-ibatis.xml]
//Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from file [E:configapplicationContext-ibatis.xml]; nested exception is java.io.FileNotFoundException: configapplicationContext-ibatis.xml (指定されたパスが見つかりません。)
//Caused by: java.io.FileNotFoundException: configapplicationContext-ibatis.xml (指定されたパスが見つかりません。)
Resource rs = new FileSystemResource("config/applicationContext-ibatis.xml");//[oms] [INFO ] 2007-12-05 08:40:18 [xml.XmlBeanDefinitionReader.loadBeanDefinitions():293] - Loading XML bean definitions from file [E:program fileseclipseofomseclipseworkspaceomsconfigapplicationContext-ibatis.xml]
BeanFactory factory = new XmlBeanFactory(rs);
// test aa = (test)factory.getBean("applicationListDao1");
// System.out.println(aa);
// ApplicationContext app = new ClassPathXmlApplicationContext("classpath:config/applicationContext-ibatis.xml");
// ApplicationContext app = new ClassPathXmlApplicationContext("classpath*:config/applicationContext-ibatis.xml");
ApplicationContext app = new ClassPathXmlApplicationContext(new String[]...{"classpath:config/applicationContext-ibatis.xml"});
// ApplicationContext app = new ClassPathXmlApplicationContext(new String[]{"config/applicationContext-ibatis.xml"});
test pp = (test)app.getBean("applicationListDao1");
String[] aa = (String[])app.getBeanDefinitionNames();
System.out.println(aa);
System.out.println(pp.getSqlMapClientTemplate().getSqlMapClient().getDataSource());
System.out.println(app instanceof Factory);
System.out.println(app == factory);
ApplicationContext app1 = new FileSystemXmlApplicationContext("classpath:config/applicationContext-ibatis.xml");
}
}
(2)另一种情况
《
spring
框架高级编程》p32
BeanFactoryAware/ApplicationContextAware
容器中多数的bean是singleton的。当一个singleton的bean需要同另一个singleton的 bean合作(使用)时,或者一个非singleton的bean需要同另一个非singleton的bean合作的时候,通过定义一个bean为另一个bean的属性来处理这种依赖的关系就足够了。然而当bean的生命周期不同的时候就有一个问题。想想一下一个singleton bean A,或许在每次方法调用的时候都需要使用一个non-singleton bean B。容器仅仅会创建这个singleton bean A一次,因此仅仅有一次的机会去设置它的属性。因此容器没有机会每次去为bean A提供新的bean B的实例。一个解决这个问题的方法是放弃一些反向控制。Bean A可以通过实现
BeanFactoryAware
知道容器的存在,使用编程的手段,在需要的时候通过调用
getBean("B")
来向容器请求新的bean B实例。对于实现了
org.springframework.beans.factory.BeanFactoryAware
接口的类, 当它被BeanFactory创建后,它会拥有一个指向创建它的BeanFactory的引用。
这允许
bean
可以以编程的方式操控创建它们的
BeanFactory
,
既可以直接使用
org.springframework.beans.factory.BeanFactory
接口,
也可以将引用强制将类型转换为已知的子类型从而获得更多的功能。这个特性主要用于编程式地取得其他
bean
。
虽然在一些场景下这个功能是有用的,但是一般来说它应该避免使用,因为它使代码与
Spring
耦合在一起,
而且也不遵循反向控制的风格(合作者应当作属性提供给
bean
)。
public interface BeanFactoryAware {
void setBeanFactory(BeanFactory beanFactory) throws BeansException;
}
2 声明式
结合SpringMVC,
以声明的方式创建ApplicationContext。在这其中也可以编程的方式取得所要Bean实例,如sqlMapClientTemplate.getSqlMapClient(),取得Bean工厂实例,sqlMapClientTemplate.getDataSource()取得数据源。
package
jp.co.oms.web.action.pdf;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.orm.ibatis.SqlMapClientTemplate;
public class test ... {
SqlMapClientTemplate sqlMapClientTemplate;
public void insert()...{
System.out.println(sqlMapClientTemplate.getDataSource());
System.out.println(sqlMapClientTemplate.getSqlMapClient());
}
public SqlMapClientTemplate getSqlMapClientTemplate() ...{
return sqlMapClientTemplate;
}
public void setSqlMapClientTemplate(SqlMapClientTemplate sqlMapClientTemplate) ...{
this.sqlMapClientTemplate = sqlMapClientTemplate;
}
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.orm.ibatis.SqlMapClientTemplate;
public class test ... {
SqlMapClientTemplate sqlMapClientTemplate;
public void insert()...{
System.out.println(sqlMapClientTemplate.getDataSource());
System.out.println(sqlMapClientTemplate.getSqlMapClient());
}
public SqlMapClientTemplate getSqlMapClientTemplate() ...{
return sqlMapClientTemplate;
}
public void setSqlMapClientTemplate(SqlMapClientTemplate sqlMapClientTemplate) ...{
this.sqlMapClientTemplate = sqlMapClientTemplate;
}
它的bean定义文件为:
<?
xml version="1.0" encoding="UTF-8"
?>
<! DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd" >
< beans >
<!-- the PropertyPlaceholderConfigurer in applicationContext.xml -->
< bean id ="dataSource" class ="org.apache.commons.dbcp.BasicDataSource" destroy-method ="close" >
< property name ="driverClassName" value ="${jdbc.driverClassName}" />
< property name ="url" value ="${jdbc.url}" />
< property name ="username" value ="${jdbc.username}" />
< property name ="password" value ="${jdbc.password}" />
</ bean >
< bean id ="transactionManager" class ="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
< property name ="dataSource" ref ="dataSource" />
</ bean >
<!-- SqlMap setup for iBATIS Database Layer -->
< bean id ="sqlMapClient" class ="org.springframework.orm.ibatis.SqlMapClientFactoryBean" >
< property name ="configLocation" value ="config/sqlmap-config.xml" />
< property name ="dataSource" ref ="dataSource" />
</ bean >
< bean id ="dao" class ="jp.co.oms.dao.ibatis.BaseDaoiBatis" >
< property name ="dataSource" ref ="dataSource" />
< property name ="sqlMapClient" ref ="sqlMapClient" />
</ bean >
< bean id ="masterDao" class ="jp.co.oms.dao.ibatis.BaseDaoiBatis" >
< property name ="dataSource" ref ="dataSource" />
< property name ="sqlMapClient" ref ="sqlMapClient" />
</ bean >
< bean id ="sqlMapClientTemplate
<! DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd" >
< beans >
<!-- the PropertyPlaceholderConfigurer in applicationContext.xml -->
< bean id ="dataSource" class ="org.apache.commons.dbcp.BasicDataSource" destroy-method ="close" >
< property name ="driverClassName" value ="${jdbc.driverClassName}" />
< property name ="url" value ="${jdbc.url}" />
< property name ="username" value ="${jdbc.username}" />
< property name ="password" value ="${jdbc.password}" />
</ bean >
< bean id ="transactionManager" class ="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
< property name ="dataSource" ref ="dataSource" />
</ bean >
<!-- SqlMap setup for iBATIS Database Layer -->
< bean id ="sqlMapClient" class ="org.springframework.orm.ibatis.SqlMapClientFactoryBean" >
< property name ="configLocation" value ="config/sqlmap-config.xml" />
< property name ="dataSource" ref ="dataSource" />
</ bean >
< bean id ="dao" class ="jp.co.oms.dao.ibatis.BaseDaoiBatis" >
< property name ="dataSource" ref ="dataSource" />
< property name ="sqlMapClient" ref ="sqlMapClient" />
</ bean >
< bean id ="masterDao" class ="jp.co.oms.dao.ibatis.BaseDaoiBatis" >
< property name ="dataSource" ref ="dataSource" />
< property name ="sqlMapClient" ref ="sqlMapClient" />
</ bean >
< bean id ="sqlMapClientTemplate
class
="org.springframework.orm.ibatis.SqlMapClientTemplate"
>
< property name ="sqlMapClient" ref ="sqlMapClient" />
</ bean >
<bean id="applicationListDao1" class="jp.co.oms.web.action.pdf.test">
<property name="sqlMapClientTemplate" ref="sqlMapClientTemplate"/>
</bean>
</ beans >
<property name="sqlMapClientTemplate" ref="sqlMapClientTemplate"/>
</bean>
</ beans >
这时另一bean定义档 ,是与页面连接方式启动的Ioc 容器。
<?
xml version="1.0" encoding="UTF-8"
?>
<! DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd" >
< beans >
< bean id ="exceptionResolver"
class ="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver" >
< property name ="exceptionMappings" >
< props >
< prop key ="jp.co.oms.service.errors.CustomSessionTimeOutException" >
omsException
</ prop >
</ props >
</ property >
</ bean >
<!-- Load WEB-INF/classes/ApplicationResources.properties for i18n messages using JSTL's fmt tag -->
< bean id ="messageSource" class ="org.springframework.context.support.ResourceBundleMessageSource" >
< property name ="basename" value ="ApplicationResources" />
</ bean >
< bean id ="viewResolver"
class ="org.springframework.web.servlet.view.InternalResourceViewResolver" >
< property name ="viewClass"
value ="org.springframework.web.servlet.view.JstlView" />
< property name ="prefix" value ="/WEB-INF/pages/" />
< property name ="suffix" value =".jsp" />
</ bean >
< bean id ="defaultHandlerMapping" class ="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
< bean name ="/content.html" class ="org.springframework.web.servlet.mvc.ParameterizableViewController" >
< property name ="viewName" value ="content" />
</ bean >
< bean name ="/masterMaintenance.html" class ="org.springframework.web.servlet.mvc.ParameterizableViewController" >
< property name ="viewName" value ="masterMaintenance" />
</ bean >
< bean name ="/cvp.html" class ="org.springframework.web.servlet.mvc.ParameterizableViewController" >
< property name ="viewName" value ="cvp" />
</ bean >
<!-- Resolver for File Upload -->
< bean id ="multipartResolver" class ="org.springframework.web.multipart.commons.CommonsMultipartResolver" >
<!-- property name="maxUploadSize" value="2097152"/ -->
</ bean >
< bean id ="urlMapping" class ="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping" >
< property name ="mappings" >
< props >
<!-- 日付選択小画面 -->
< prop key ="/smallDateChoose.html" > smallDateChooseController </ prop >
</ props >
</ property >
</ bean >
< bean id ="smallDateChooseController" class ="jp.co.oms.web.action.SmallDateChooseController" >
< property name ="validator" ref ="beanValidator" />
< property name ="commandName" >< value > masterCommand </ value ></ property >
< property name ="commandClass" >< value > jp.co.oms.model.SmallDateChoose </ value ></ property >
< property name ="pageId" >< value > POP_SP06 </ value ></ property >
< property name ="formView" >< value > smallDateChoose </ value ></ property >
< property name ="smallDateChooseManager" >< ref bean ="smallDateChooseManager" /></ property >
<property name="applicationListDao1"><ref bean="applicationListDao1"/></property>
</ bean >
</ beans >
<! DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd" >
< beans >
< bean id ="exceptionResolver"
class ="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver" >
< property name ="exceptionMappings" >
< props >
< prop key ="jp.co.oms.service.errors.CustomSessionTimeOutException" >
omsException
</ prop >
</ props >
</ property >
</ bean >
<!-- Load WEB-INF/classes/ApplicationResources.properties for i18n messages using JSTL's fmt tag -->
< bean id ="messageSource" class ="org.springframework.context.support.ResourceBundleMessageSource" >
< property name ="basename" value ="ApplicationResources" />
</ bean >
< bean id ="viewResolver"
class ="org.springframework.web.servlet.view.InternalResourceViewResolver" >
< property name ="viewClass"
value ="org.springframework.web.servlet.view.JstlView" />
< property name ="prefix" value ="/WEB-INF/pages/" />
< property name ="suffix" value =".jsp" />
</ bean >
< bean id ="defaultHandlerMapping" class ="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
< bean name ="/content.html" class ="org.springframework.web.servlet.mvc.ParameterizableViewController" >
< property name ="viewName" value ="content" />
</ bean >
< bean name ="/masterMaintenance.html" class ="org.springframework.web.servlet.mvc.ParameterizableViewController" >
< property name ="viewName" value ="masterMaintenance" />
</ bean >
< bean name ="/cvp.html" class ="org.springframework.web.servlet.mvc.ParameterizableViewController" >
< property name ="viewName" value ="cvp" />
</ bean >
<!-- Resolver for File Upload -->
< bean id ="multipartResolver" class ="org.springframework.web.multipart.commons.CommonsMultipartResolver" >
<!-- property name="maxUploadSize" value="2097152"/ -->
</ bean >
< bean id ="urlMapping" class ="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping" >
< property name ="mappings" >
< props >
<!-- 日付選択小画面 -->
< prop key ="/smallDateChoose.html" > smallDateChooseController </ prop >
</ props >
</ property >
</ bean >
< bean id ="smallDateChooseController" class ="jp.co.oms.web.action.SmallDateChooseController" >
< property name ="validator" ref ="beanValidator" />
< property name ="commandName" >< value > masterCommand </ value ></ property >
< property name ="commandClass" >< value > jp.co.oms.model.SmallDateChoose </ value ></ property >
< property name ="pageId" >< value > POP_SP06 </ value ></ property >
< property name ="formView" >< value > smallDateChoose </ value ></ property >
< property name ="smallDateChooseManager" >< ref bean ="smallDateChooseManager" /></ property >
<property name="applicationListDao1"><ref bean="applicationListDao1"/></property>
</ bean >
</ beans >