005.初始化IoC容器(基于XML配置Bean 利用无参构造方法实例化对象)02

1.src/main/resources(applicationContext.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标签的作用是用于通知IOC容器实例化那个对象-->
    <!--class代表从那个类实例化-->
    <!--id代表标识-->
    <bean id="apple1" class="com.imooc.spring.ioc.entity.Apple">

    </bean>

</beans>

2. src/main/java/com/imooc/spring/ioc/(SpringApplication.java)如果bean中不写属性,默认调用无参构造

package com.imooc.spring.ioc;


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringApplication
{
    public static void main(String[] args)
    {

        //创建SpringIoc容器,并根据配置文件在容器中实例化
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");

    }
}
package com.imooc.spring.ioc.entity;

public class Apple
{
    private String title;
    private String color;
    private String origin;

    public Apple()
    {
        //如果bean中不写属性,默认调用构造方法
        System.out.println("Apple对象已创建," + this);
    }

    public Apple(String title, String color, String origin)
    {
        this.title = title;
        this.color = color;
        this.origin = origin;
    }

    public String getTitle()
    {
        return title;
    }

    public void setTitle(String title)
    {
        this.title = title;
    }

    public String getColor()
    {
        return color;
    }

    public void setColor(String color)
    {
        this.color = color;
    }

    public String getOrigin()
    {
        return origin;
    }

    public void setOrigin(String origin)
    {
        this.origin = origin;
    }
}

 

posted @ 2022-11-21 23:20  李林林  阅读(13)  评论(0编辑  收藏  举报