1.springIOC初識

來源:互聯網
上載者:User

標籤:utf-8   全路徑   5.x   print   contex   設定檔   highlight   配置   建立對象   

IOC,控制反轉,從最淺顯的角度來講就是通過Spring容器來負責建立對象

大體的實現結構

1.首先有一個我們需要啟動並執行類

2.在spring專屬的xml設定檔中配置該類

3.啟動容器 

4.從該容器中擷取此類的對象

5.調用對象的方法

簡單demo

1.導包,最基本的是spring.jar和commons-logging.jar

2.建立我們需要啟動並執行類

public class HelloWorld {public void hello(){System.out.println("hello world");}}

3.編寫applicationContext.xml設定檔

<?xml version="1.0" encoding="UTF-8"?><!--beans裡面的每個bean就是一個需要容器啟動的類 --><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一般都命名為該類名的首字母小寫名字--><bean id="helloWorld" class="HelloWorld的全類名"></bean>    <!--每一個alias都是一個別名,name就是上面定義的id,alias就是別名--><alias name="helloWorld" alias="王五"/><alias name="helloWorld" alias="林志玲"/><alias name="helloWorld" alias="趙六"/></beans>

4.啟動容器,擷取對象,調用方法

public class HelloWorldTest {@Testpublic void test(){/* * 1、啟動spring容器 * 2、從spring容器中把helloWorld拿出來 * 3、對象.方法 *///啟動spring容器ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");//設定檔的全路徑HelloWorld helloWorld = (HelloWorld)context.getBean("helloWorld");//根據設定檔中的id擷取對象helloWorld.hello();}}

  

1.springIOC初識

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.