Spring:IOC—控制反转(3)

本文介绍如何使用Spring框架的IOC容器通过带有参数的构造方法创建对象,并演示了三种配置方式:根据构造方法参数下标、参数名称及参数类型进行设置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

IOC创建对象的三种方法
第二种:通过有参的构造方法创建对象

Hello.java

package com.et.bean;

public class Hello {

    private String name;

    //带参数的构造方法
    public Hello(String name){
        super();
        this.name=name;
    }

    public void show(){
        System.out.println("hello,"+name);
    }

}

Test.java基本不变


package com.et.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.et.bean.Hello;

public class Test {
    public static void main(String[] args) {
        ApplicationContext act=new ClassPathXmlApplicationContext("beans.xml");
        Hello hello=(Hello)act.getBean("hello");
        hello.show();
    }
}

有参数的构造方法创建对象又可以分为三种:
bean.xml

1.根据构造方法参数下标

<?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
        http://www.springframework.org/schema/beans/spring-beans.xsd">
        <bean id="hello" class="com.et.bean.Hello">
            <!-- 根据构造方法参数下标:参数下标从0开始 -->
            <constructor-arg index="0" value="elliott"/>
        </bean>
</beans>

2.根据参数名称来设置

<?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
        http://www.springframework.org/schema/beans/spring-beans.xsd">
        <bean id="hello" class="com.et.bean.Hello">
            <!-- 根据参数名称 -->
            <constructor-arg name="name" value="elliott"/>
        </bean>
</beans>

3.根据参数类型来设置

<?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
        http://www.springframework.org/schema/beans/spring-beans.xsd">

        <bean id="hello" class="com.et.bean.Hello">
            <!-- 根据参数类型 -->
            <constructor-arg type="java.lang.String" value="elliott"></constructor-arg>
        </bean>
</beans>

输出结果都为:
hello,elliott

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值