Spring
核心:
IOC(控制反轉)
--將控制管理權不禁JavaBean管理,交給Spring容器管理
DI(依賴注 web
--分層
--上層依賴於下層(栗子:Dao層服務於Service服務於Action)
--下層服務於上層)spring
Spring環境搭建app
1.下載Spring框架框架
下載地址:http://repo.spring.io/release/org/springframework/spring/測試
2.建立web項目 導入Jar包spa
2.在src目錄建立spring配置文件prototype
--applicationContext.xml(默認配置文件名稱)
or--spring.xml(可自定義名稱)code
<?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.xsd"> <!--將JavaBean的控制權交由Spring管理--> <bean name="DataBean" class="com.spring.model.DataBean" scope="prototype">
<property name="name" value="Spring" />
</bean >
</beans>
3.建立beanxml
bean的單例&多例
scope="singleton"[單例] | "prototype"[多例]
使用場合:在對象常常發生改變時,要使用多例對象
<bean name="hello(key)" class="com.xxx.xxx(類全名)" scope="singleton(是否單例 默認是)" > <!-- 屬性注入--> <property name="name" value="Spring" /> </bean>
4.測試
* ApplicationContext
--在加載Spring配置文件時就建立了bean
* BeanFactory
--在使用了某個bean時才建立
@Test public void test01(){ //加載spring.xml // ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml"); BeanFactory factory = new ClassPathXmlApplicationContext("spring.xml"); // DataBean dataBean =(DataBean) factory.getBean("DataBean"); //獲取bean DataBean dataBean= factory.getBean("DataBean",DataBean.class); System.out.println(dataBean.getName()); }
5.運行結果:Spring