spring的學習日記-spring-IOC的理解-的入門-Hello World2
阿新 • • 發佈:2022-03-04
基於xml配置實現有參構造建立物件
有參構造建立物件的方式有3種,本例子採用有參構造創建物件----通過引數名,建構函式方式給引數賦值-----推薦使用這種方式
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 + '\'' + '}'; } }
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 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>--> <!-- 註冊Bean就相當於new一個物件--> <!-- 有參構造建立物件方式1:通過實體類的引數名,建構函式引數解析————————>推薦使用這種方式--> <bean id="hello" class="com.fu.pojo.Hello"> <constructor-arg 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); } }
測試結果:
總結:我們通過有參構造建立物件時,bean標籤就是例項化物件,使用constructor-arg標籤給物件賦值