Spring全回顧之HelloWrold
阿新 • • 發佈:2019-01-23
Spring作為一個java程式設計師不可繞的過優秀框架,我們應該向掌握JDk一樣掌握Spring。
作為認識Spring開始,那就從Spring HelloWorld開始
首先匯入Spring所需要的4個基礎jar包,以及一個loging依賴jiar包
commons-logging-1.2.jarspring-beans-5.0.6.RELEASE.jar
spring-context-5.0.6.RELEASE.jar
spring-core-5.0.6.RELEASE.jar
spring-expression-5.0.6.RELEASE.jar
首先建立一個HelloWorld類
package com.kk.spring.beans; public class HelloWorld { private String name; public void setName(String name) { this.name = name; } public void hell(){ System.out.println("hello: "+name); } }
然後建立一個spring的配置檔案,名為applicaContext.xml放在src目錄下,配置如下內容
這裡我推薦使用spring tools suite 的外掛來方便的完成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" xmlns:util="http://www.springframework.org/schema/util" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd"> <!-- 配置bean class: bean的全類名,通過反射的方式在IOC容器中建立bean,所以要求Bean中有無參構造方法 id : 標識容器中的Bean,id 唯一 --> <bean id="helloWorld" class="com.kk.spring.beans.HelloWorld"> <property name="name" value="Spring...."></property> </bean> </beans>
這樣就配置好了Spring,也就是把HelloWorld這個類交給了Spring管理,使用時不像以前那樣new出來而是從Spring容器裡取出來直接使用。
接下寫一個測試類看看效果
package com.kk.spring.beans; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class test { public static void main(String[] args) { //1.建立Spring的IOC容器物件 //ApplicationConText 代表IOC容器 //ClassPathXmlApplicationContext是ApplicationConText介面的實現類,該實現類從類路勁下來載入配置檔案 ApplicationContext ctx = new ClassPathXmlApplicationContext("applicaContext.xml"); //2.從IOC容器中獲取Bean例項 //用id定位到IOC容器中的Bean HelloWorld helloWorld = (HelloWorld) ctx.getBean("helloWorld"); //用型別返回IOC容器中的Bean,但是要求IOC容器中必須只能有一個該型別的Bean //HelloWorld helloWorld = ctx.getBean(HelloWorld.class); System.out.println(helloWorld); //3.呼叫hell方法 helloWorld.hell(); } }
細節:Spring容器給HelloWorld的name屬性設定值時是使用的set方法把值注入如果把HelloWorld中的set方法改名Spring容器會報錯,當然還有其他方法來給屬性設值如構造方法等