详解SpringBean基于XML的装配

1.设值注入:通过反射调用setXxx注入属性值

package com.itheima.assemble;
import java.util.List;
public class User {
	private String username;
	private Integer password;
	private List list;
	/**
	 * 设值注入 
	 * 提供默认空参构造方法 ;
	 * 为所有属性提供setter方法。
	 */
	public User() {
		super();
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public void setPassword(Integer password) {
		this.password = password;
	}
	public void setList(List list) {
		this.list = list;
	}
	@Override
	public String toString() {
		return "User [username=" + username + ", password=" + password +
				", list=" + list + "]";
	}

}
package com.itheima.assemble;
import org.springframework.context.ApplicationContext;
import 
	org.springframework.context.support.ClassPathXmlApplicationContext;
public class XmlBeanAssembleTest {
	public static void main(String[] args) {
		String xmlPath = "com/itheima/assemble/beans5.xml";
		ApplicationContext applicationContext = 
						new ClassPathXmlApplicationContext(xmlPath);
		// 构造方式输出结果
		System.out.println(applicationContext.getBean("user2"));
	}
}


 	
	
	
		
		
		
		
			
				"值1"
				"值2"
			
		
	

在这里插入图片描述

2.构造注入:用+其value属性注入属性值

package com.itheima.assemble;
import java.util.List;
public class User {
	private String username;
	private Integer password;
	private List list;
	/**
	 * 用构造注入 
	 * 创建带所有参数的有参构造方法。
	 */
	public User(String username, Integer password, List list) {
		super();
		this.username = username;
		this.password = password;
		this.list = list;
	}

	@Override
	public String toString() {
		return "User [username=" + username + ", password=" + password +
				", list=" + list + "]";
	}
}
package com.itheima.assemble;
import org.springframework.context.ApplicationContext;
import 
	org.springframework.context.support.ClassPathXmlApplicationContext;
public class XmlBeanAssembleTest {
	public static void main(String[] args) {
		String xmlPath = "com/itheima/assemble/beans5.xml";
		ApplicationContext applicationContext = 
						new ClassPathXmlApplicationContext(xmlPath);
		// 构造方式输出结果
		System.out.println(applicationContext.getBean("user1"));
	}
}


 	
	
	
		
		 
		  
			
				"值1"
				"值2"
			
		
	

在这里插入图片描述

到此这篇关于详解SpringBean基于XML的装配的文章就介绍到这了,更多相关SpringBean装配内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

你可能感兴趣的:(详解SpringBean基于XML的装配)