spring的学习日记-spring-IOC的理解-的入门-Hello World-无参构造实现(set方式注入,重点)

Spring-基于xml实现Hello World-通过无参构造创建对象,使用set方法进行赋值

在本例子中,我们采用无参构造创建对象:

  通过上述例子我们可以发现IOC中,通过bean标签创建一个对象,通过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属性为对应包下面的类的路径,使用全包名+类名

 

posted @ 2022-03-04 15:33  Fu_Zhang  阅读(41)  评论(0)    收藏  举报