spring的學習日記-spring-IOC的理解-的入門-Hello World
阿新 • • 發佈:2022-03-04
Spring-基於xml實現Hello World-通過無參構造建立物件,使用set方法進行賦值
pojo層:
package com.fu.pojo; public class Hello { private String str; public Hello() { System.out.println("通過無參構造建立物件"); } public Hello(String str) { this.str = str; System.out.println("通過有參構造建立物件"); }public String getStr() { return str; } public void setStr(String str) { this.str = str; System.out.println("通過Set方法進行賦值"); } @Override public String toString() { return "Hello{" + "str='" + str + '\'' + '}'; } }
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 https://www.springframework.org/schema/beans/spring-beans.xsd"><!-- 註冊bean,註冊一個bean就相當於new一個物件--> <bean id="hello" class="com.fu.pojo.Hello"> <property name="str" value="Hello World!"/> </bean> </beans>
測試類:
import com.fu.pojo.Hello; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /* IOC建立物件的方式:無參構造物件:1種,通過set方法進行賦值 有參構造物件:3種 */ public class MyTest { public static void main(String[] args) { //獲取IOC容器 ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); //有了容器以後,我們通過getbean得到什麼就是什麼 Hello hello = context.getBean("hello", Hello.class); System.out.println(hello); } }
測試結果:
總結:在Spring中,我們不再使用new關鍵字建立物件,而是在Spring的xml配置檔案中使用Bean標籤建立物件,
在bean標籤中id屬性全域性唯一,註冊到IOC容器中,class屬性為對應包下面的類的路徑,使用全包名+類名
在本例子中,我們採用無參構造建立物件:
通過上述例子我們可以發現IOC中,通過bean標籤建立一個物件,通過set方法進行賦值