Spring框架 4.3.6環境搭建


Spring
核心:
IOC(控制反轉)
  --將控制管理權不由JavaBean管理,交給Spring容器管理
DI(依賴注 

 --分層
    --上層依賴於下層(栗子:Dao層服務於Service服務於Action)
    --下層服務於上層)

Spring環境搭建

  1.下載Spring框架

  下載地址:http://repo.spring.io/release/org/springframework/spring/

  2.創建web項目 導入Jar包

  

  2.在src目錄創建spring配置文件

  --applicationContext.xml(默認配置文件名稱)
   or--spring.xml(可自定義名稱)

<?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.創建bean

    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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM