spring簡介
spring是一個優秀的框架,它的核心是控制反轉和依賴注入。所謂控制反轉是指,應用本身不負責依賴對象的創建及維護,依賴對象的創建和維護是由外部容器負責的,控制權的轉移就是控制反轉;依賴注入是指,由外部容器動態的將依賴對象注入到組件中。
優點:①降低組件之間的耦合度,實現軟件各層之間的解耦。
②使用容器爲其提供衆多服務,事務管理服務(開啓和關閉事務)、JMS服務、持久化服務、spring core 核心服務等。
③容器提供單例模式的支持,開發人員不在需要自己編寫實現代碼。
④容器提供AOP技術,利用他容易實現權限攔截等功能。
⑤提供輔助類,JDBCtemplate, HibernateTemplate,能加快應用的開發。
⑥對於主流框架提供了集成支持。
界定一個框架是輕或者重的框架,是看使用它時,它開啓的服務的多少來決定的。
spring開發環境的搭建
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="personService" class="cn.itcast.service.impl.PersonServiceBean"></bean>
</beans>
配置好bean之後,該bean就被spring容器管理。 調用
spring實例化bean的三種方式:
一、使用構造器實例化;
- <!--applicationContext.xml配置:-->
- <bean id="personService" class="cn.mytest.service.impl.PersonServiceBean"></bean>
二、使用靜態工廠方法實例化;
- public void instanceSpring(){
- //加載spring配置文件
- ApplicationContext ac = new ClassPathXmlApplicationContext(
- new String[]{
- "/conf/applicationContext.xml"
- });
- //調用getBean方法取得被實例化的對象。
- PersonServiceBean psb = (PersonServiceBean) ac.getBean("personService");
- psb.save();
- }
三、使用實例化工廠方法實例化。
- package cn.mytest.service.impl;
- /**
- *創建工廠類
- *
- */
- public class PersonServiceFactory {
- //創建靜態方法
- public static PersonServiceBean createPersonServiceBean(){
- //返回實例化的類的對象
- return new PersonServiceBean();
- }
- }
- <!--applicationContext.xml配置:-->
- <bean id="personService1" class="cn.mytest.service.impl.PersonServiceFactory" factory-method="createPersonServiceBean"></bean>
- public void instanceSpring(){
- //加載spring配置文件
- ApplicationContext ac = new ClassPathXmlApplicationContext(
- new String[]{
- "/conf/applicationContext.xml"
- });
- //調用getBean方法取得被實例化的對象。
- PersonServiceBean psb = (PersonServiceBean) ac.getBean("personService1");
- psb.save();
- }