spring的学习日记-spring-IOC的理解-的入门-Hello World3-有参构造实现方式3
基于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>--> <!-- 有参构造实现方式二:通过下标实现赋值--> <!-- <bean id="hello" class="com.fu.pojo.Hello">--> <!-- <constructor-arg index="0" value="Hello World-有参构造方法二"/>--> <!-- </bean>--> <!-- 有参构造实现方式三:通过参数的类型实现,因为参数的类型相同时,将无法处理————————不推荐使用这种方式--> <bean id="hello" class="com.fu.pojo.Hello"> <constructor-arg type="java.lang.String" value="Hello World实现方式3-类型实现"/> </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); } }
测试结果:


浙公网安备 33010602011771号