spring IOC——注入构造方法

applicationContext中type是两个String类型,所以注入的是两个String的构造方法

<?xml version="1.0" encoding="UTF-8"?>
<beans
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

	<bean id="test" class="com.test.Test">
		<constructor-arg type="java.lang.String" value="superMan"/>
		<constructor-arg type="java.lang.String" value="smallMan"/>
	</bean>
	
	<bean id="run" class="com.run.TestRun">
		<property name="test_run" ref="test"></property>
	</bean>
</beans>

TestRun

package com.run;

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

import com.test.Test;

public class TestRun {

	Test test_run;
	
	public Test getTest_run() {
		return test_run;
	}
	
	public void setTest_run(Test test_run) {
		this.test_run = test_run;
	}
	
	public static void main(String[] args) {
		//取得应用程序上下文接口
		ApplicationContext apl = new ClassPathXmlApplicationContext("applicationContext.xml");
		//从IOC容器中取出指定的Bean
		TestRun run = (TestRun) apl.getBean("run");
	}
}

Test

package com.test;

public class Test {

	//声明重载的构造方法
	public Test(String name, int age){
		System.out.println("在string+int中"+"name:"+name+"  age:"+age);
	}
	
	public Test(String name, String realname){
		System.out.println("在string+string中"+"name:"+name+"  realname:"+realname);
	}
}

猜你喜欢

转载自blog.csdn.net/Milan__Kundera/article/details/82082859