03_构造注入

【工程截图】

【HelloWorld.java】

package com.HigginCui;

public class HelloWorld {
    private String name;
    private String words;
    //建议加上无参构造函数
    public HelloWorld(){}
    
    public HelloWorld(String name,String words){
        this.name=name;
        this.words=words;
    }
    
    public String toString() {
        return "HelloWorld [name=" + name + ", words=" + words + "]";
    }
}

【applicationContext.xml】

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:aop="http://www.springframework.org/schema/aop"
       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-2.5.xsd
           http://www.springframework.org/schema/aop 
           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
    <!-- 
        <constructor-arg>:表示将使用Constructor Injection
        在bean定义文件中使用Constructor Injection时,在设定上必须指定构造方法上参数的顺序index
        index:用于指定对象将注入至构造方法中哪一个位置的参数
     -->
    <bean id="helloWorld" class="com.HigginCui.HelloWorld">
        <constructor-arg index="0">
            <value>张三</value>
        </constructor-arg>
        <constructor-arg index="1">
            <value>你好!</value>
        </constructor-arg>
    </bean>
</beans>

【testHelloWorld.java】

package com.HigginCui.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.HigginCui.HelloWorld;

public class testHelloWorld {
    @Test
    public void testHelloWorld(){
        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
        HelloWorld helloWorld=(HelloWorld) context.getBean("helloWorld");
        System.out.println(helloWorld.toString());
    }
}

【运行结果】

HelloWorld [name=张三, words=你好!]
原文地址:https://www.cnblogs.com/HigginCui/p/5573491.html