Spring的 构造函数注入 和 属性注入

Spring IOC支持 构造函数注入 和 属性注入

 

构造函数注入如下:

package test;

public class testImpl implements testInter {
	
	private String Username;
	private String Password;
	
	@Override
	public void setUsername(String string) {
		// TODO Auto-generated method stub
		this.Username = string;
	}

	@Override
	public void setPassword(String string) {
		// TODO Auto-generated method stub
		this.Password = string;
	}
	
	@Override
	public String getUsername() {
		// TODO Auto-generated method stub
		return Username;
	}

	@Override
	public String getPassword() {
		// TODO Auto-generated method stub
		return Password;
	}

	public testImpl(){            //the constructor of not have arguments
		
	}
	
	//这里自定义的构造函数testImpl(User user)依赖于User对象

	public testImpl(User user){    //the constructor of have arguments
		this.Username=user.username;
		this.Password=user.password;
	}
	
	

}

User对象如下:

package test;

public class User {
	public String username = "小明";
	public String password = "12345678";
	
}

配置文件设置如下:






	  //设置构造函数参数
	


	


编写测试程序:

package test;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class test1 {

	public static void main(String[] args) {
		BeanFactory factory = new ClassPathXmlApplicationContext("tt.xml");
		testImpl tb2 = (testImpl)factory.getBean("testBean2");	
		System.out.println("这是"+tb2.getUsername()+"的银行卡"+"\n密码是"+tb2.getPassword());
	}

}

测试输入结果:

 

属性注入如下:

编写bean类

package test;

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class TestAttibuteSet {
	private Map map;
	private List list;
	private Set set;
	private Properties properties;
	
	public void setmap(Map map){
		this.map = map;
	}
	
	public void setlist(List list){
		this.list = list;
	}
	
	public void setset(Set set){
		this.set=set;
	}
	
	
	public void setproperties(Properties properties){
		this.properties = properties;
	}
	
	public String get(){
		return ("map"+map.entrySet()+"\n" + "properties:"+properties.getProperty("key1")+"\n"
				+ "set:"+ set+"\n"+"list:"+list).toString();
	}
}

 

在配置文件里设置配置信息:






	
		
			
				I am coming !
			
			
				spring !
			
		
	
	
		
			星期一
			星期二
			星期三
		
	
	
		
			周一
			周二
			周三
		
	
	
		
			123
			456
			789
		
	

编写测试类:

package test;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class testtas {

	public static void main(String[] args) {
		BeanFactory factory = new ClassPathXmlApplicationContext("tt.xml");
		TestAttibuteSet TAS = (TestAttibuteSet)factory.getBean("tas");	
		System.out.println(TAS.get());
	}

}

测试结果输出:

Spring的 构造函数注入 和 属性注入_第1张图片

注入成功

你可能感兴趣的:(spring)