Spring:IOC—控制反转(3)

来源:互联网 发布:怎么网络推广 编辑:程序博客网 时间:2024/04/30 12:14

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

原创粉丝点击