Spring对象属性注入

注入--对象属性赋值

一:基础数据的set注入

1)实体类User

public class User {

	private int age;
	private String username;
	private String password;
}

对User类添加setter/getter

2)配置文件,比如叫beans.xml



	
	
		
			25
		
		
			Tom
		
		
			123456
		
	
}

3)测试类UserTest

public class UserTest {
	
	/**
	 * 测试基础数据类型的set注入
	 * */
	public static void main(String[] args) {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("/beans.xml");
		User user = ctx.getBean("user",User.class);// 自己不用进行类型转换
		System.out.println(user);
		System.out.println(user.getAge());
		System.out.println(user.getUsername());
		System.out.println(user.getPassword());
	}
}

二:基础数据类型的构造器注入(构造方法)

1)实体类Student

public class Student {

	private int age;
	private String username;
	private String password;

	// 明写缺省构造方法
	public Student() {
	}

	// 重写构造方法
	public Student(String username, String password) {
		this.username = username;
		this.password = password;
	}

	// 重写构造方法
	public Student(int age, String username, String password) {
		this.age = age;
		this.username = username;
		this.password = password;
	}
}

2)配置文件


		
		
		
	

如果是多构造器,应该指定参数的类型和顺序


		

3)测试类SrudentTest

public class StudentTest {

	/**
	 * 测试基础数据类型的构造方法注入
	 * */
	public static void main(String[] args) {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("/beans.xml");
		Student student = ctx.getBean("student",Student.class);
		System.out.println(student);
		System.out.println(student.getAge());
		System.out.println(student.getUsername());
		System.out.println(student.getPassword());
	}
}

三:特殊数据类型的注入

1)实体类Person

public class Person {

	private String name;
	private int age;
	private double money;
	private List list;
	private Set set;
	private Map map;
	private String[] array;
	private Properties properties;
	private User user;
}

为Person类增加setteer/getter

2)配置文件


		
			Tom
		
		
			28
		
		
			100.9
		
		
			
				shandong
				杭州
				xihu
			
		
		
			
				13900
				13900
				13800
			
		
		
			
				
					
						key1
					
					value1
				
				
				
			
		
		
			
				xiaoh
				xiaob
			
		
		
			
				pp1Value
				pp2Value
			
		
		
			
		
	
3)测试类PersonTest
public class PersonTest {

	public static void main(String[] args) {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("/beans.xml");
		Person person = ctx.getBean("person",Person.class);
		System.out.println(person);
		System.out.println(person.getName());
		System.out.println(person.getAge());
		System.out.println(person.getMoney());
		System.out.println(person.getList());
		System.out.println(person.getSet());
		System.out.println(person.getMap());
		System.out.println(person.getArray());
		System.out.println(person.getProperties());
		System.out.println(person.getUser());
		System.out.println(person.getUser().getUsername());
	}
}


你可能感兴趣的:(Spring)