Spring框架学习之第8节
<bean id=”foo” class=”…Foo”>
<property name=”属性”>
<!—第一方法引用-->
<ref bean=”bean对象名”>
<!—内部bean—>
<bean>
<property></property>
</bean>
</property>
</bean>
④集成配置
public class Student
public class Graduate extends Student
在beans.xml文件中配置
思考:目前我们都是通过set的方式给bean注入值的,spring还提供了其他的方式注入值,通过构造函数注入值
- 通过构造函数注入值
 
beans.xml文件关键代码
<!-- 配置一个雇员对象 -->
<bean id="employee" class="com.litao.constructor.Employee">
<!-- 通过构造函数来注入属性值 index代表第几个参数,type是类型 -->
<constructor-arg index="0" type="java.lang.String" value="大明"/>
<constructor-arg index="1" type="int" value="23"/>
</bean>
set注入的缺点是无法清晰表达哪些属性是必须的,哪些是可选的,构造注入的优势是通过构造强制依赖关系,不可能实例化不完全的或无法使用的bean。
- 自动装配bean的属性值
 


(1) byName的用法
<!-- 配置一个master对象 -->
<bean id="master" class="com.litao.autowire.Master" autowire="byName">
<property name="name">
<value>顺平</value>
</property>
<!--
/* 传统的方法 */
<property name="dog" ref="dog" />
-->
</bean>
<!-- 配置dog对象 -->
<bean id="dog" class="com.litao.autowire.Dog">
<property name="name" value="小黄" />
<property name="age" value="3" />
</bean>
原理图:

(1) byType
寻找和属性类型相同的bean,找不到,装不上,找到多个抛异常
(2) constructor:autowire="constructor"
说明:
查找和bean的构造参数一致的一个或多个bean,若找不到或找到多个,抛异常。按照参数的类型装配。
(3) autodetect:autowire="autodetect"
说明:(3)和(2)之间选一个方式。不确定
性的处理与(3)和(2)一致。
(4) defualt
这个需要在<beans defualt-autorwire=“指定” />
当你在<beans>指定了default-autowire后,所有的bean的默认的autowire就是指定的装配方法
如果没有在<beans defualt-autorwire=“指定” />,没有default-autowire=”指定”,则默认是default-autowire=”no”.
(5) no:不自动装配
使用spring的特殊bean,完成分散配置
beans.xml
说明:当通过context:property-placeholder引入多个属性文件的时候使用逗号间隔
<!-- 引入我们的db.properties文件 -->
<context:property-placeholder location="classpath:com/litao/dispatch/db.properties,classpath:com/litao/dispatch/db2.properties"/>
<!-- 配置一个DButil对象 -->
<bean id="dbutil" class="com.litao.dispatch.DBUtil">
<property name="name" value="${name}" />
<property name="drivername" value="${drivername}" />
<property name="url" value="${url}" />
<property name="pwd" value="${pwd}" />
</bean>
<!-- 配置一个DButil2对象 -->
<bean id="dbutil2" class="com.litao.dispatch.DBUtil">
<property name="name" value="${db2.name}" />
<property name="drivername" value="${db2.drivername}" />
<property name="url" value="${db2.url}" />
<property name="pwd" value="${db2.pwd}" />
</bean>
db.properties
name=scott
drivername=oracle:jdbc:driver:OracleDriver
url=jdbc:oracle:thin:@127.0.0.1:1521:hsp
pwd=tiger
#key=value
项目结构:

/******************************com.litao.autowire包***************************************************/
com.litao.autowire.App1.java
package com.litao.autowire; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class App1 { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ac = new ClassPathXmlApplicationContext("com/litao/autowire/beans.xml");
//通过容器获取主人
Master master = (Master) ac.getBean("master");
System.out.println(master.getName()+" "+master.getDog().getName()); } }
com.litao.autowire.Dog.java
package com.litao.autowire;
import javax.annotation.Resource;
public class Dog {
	private String name;
	private int age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}
com.litao.autowire.Master.java
package com.litao.autowire;
public class Master {
	private String name;
	private Dog dog;
	public Master(Dog dog){
		System.out.println("Master(Dog dog)构造函数被调用");
		this.dog = dog;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Dog getDog() {
		return dog;
	}
	public void setDog(Dog dog) {
		this.dog = dog;
	}
}
com.litao.autowire.beans.xml
<?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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"
default-autowire="no"
> <!-- 配置一个master对象 -->
<bean id="master" class="com.litao.autowire.Master">
<property name="name">
<value>顺平</value>
</property>
<!--
/* 传统的方法 */
<property name="dog" ref="dog" />
-->
</bean>
<!-- 配置dog对象 -->
<bean id="dog11" class="com.litao.autowire.Dog">
<property name="name" value="小黄" />
<property name="age" value="3" />
</bean> </beans>
/******************************com.litao.collection包***************************************************/
App1.java
package com.litao.collection; import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Map.Entry; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class App1 { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ac = new ClassPathXmlApplicationContext("com/litao/collection/beans.xml"); Department department = (Department)ac.getBean("department");
System.out.println(department.getName());
for (String emName : department.getEmpName()) {
System.out.println(emName);
} System.out.println("************通过list集合取出数据**************");
for(Employee e: department.getEmpList()){ System.out.println("name=" + e.getName() + " " + e.getId()); } //set取得时候不能保证顺序,list取时可以保证顺序
System.out.println("************通过set集合取出数据**************");
for(Employee e: department.getEmpsets()){ System.out.println("name=" + e.getName()); }
System.out.println("************通过map集合取出数据**************");
//1.用迭代器
Map<String,Employee> empmaps = department.getEmpMaps(); Iterator it = empmaps.keySet().iterator(); while (it.hasNext()) {
String key = (String)it.next();
//System.out.println(key);
Employee emp = empmaps.get(key);
System.out.println("key="+key+" "+emp.getName());
} //2.最简洁的方法
for(Entry<String,Employee> entry1:department.getEmpMaps().entrySet()){
System.out.println(entry1.getKey() + " " + entry1.getValue().getName()); } System.out.println("**************通过Properties取出数据**************");
Properties pp = department.getPp();
//System.out.println(pp.getProperty("pp1").toString());
for(Entry<Object,Object> entry:pp.entrySet()){
System.out.println(entry.getKey().toString()+" "+ entry.getValue().toString());
}
System.out.println("**************通过Enumeration取出数据**************"); Enumeration en = pp.keys();
while (en.hasMoreElements()) {
//Entry<Object,Object> element = (Entry<Object,Object>) en.nextElement();
//System.out.println(element.getKey()+ " " +element.getValue()); String key = (String)en.nextElement(); System.out.println(key+ " " + pp.getProperty(key));
} } }
Department.java
package com.litao.collection; import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set; public class Department { private String name;
private String[] empName;
private List<Employee> empList;
private Set<Employee> empsets;
private Map<String,Employee> empMaps;
private Properties pp;//Properties的配置使用 public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String[] getEmpName() {
return empName;
}
public void setEmpName(String[] empName) {
this.empName = empName;
} public List<Employee> getEmpList() {
return empList;
}
public void setEmpList(List<Employee> empList) {
this.empList = empList;
}
public Set<Employee> getEmpsets() {
return empsets;
}
public void setEmpsets(Set<Employee> empsets) {
this.empsets = empsets;
}
public Map<String, Employee> getEmpMaps() {
return empMaps;
}
public void setEmpMaps(Map<String, Employee> empMaps) {
this.empMaps = empMaps;
}
public Properties getPp() {
return pp;
}
public void setPp(Properties pp) {
this.pp = pp;
} }
Employee.java
package com.litao.collection;
public class Employee {
    private String name;
    private int id;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
}
beans.xml
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <bean id="department" class="com.litao.collection.Department">
<property name="name" value="财务部" />
<!-- 给数组注入值 -->
<property name="empName">
<list>
<value>小明</value>
<value>小明小明</value>
<value>小明小明小明小明</value>
</list>
</property>
<!-- 给list注入值 list中可以有相同的对象 -->
<property name="empList">
<list>
<ref bean="emp1"/>
<ref bean="emp2"/>
<ref bean="emp2"/>
<ref bean="emp2"/>
<ref bean="emp2"/>
</list>
</property>
<!-- 给set注入值 set中不能有相同的对象 -->
<property name="empsets">
<set>
<ref bean="emp1"/>
<ref bean="emp2"/>
<ref bean="emp2"/>
<ref bean="emp2"/>
<ref bean="emp2"/>
<ref bean="emp2"/>
</set>
</property>
<!-- 给map注入值 map中也不能有相同的对象,后面的会把前面的覆盖,map只要key一样就可以装配value对应的bean -->
<property name="empMaps">
<map>
<entry key="1" value-ref="emp1"></entry>
<entry key="2" value-ref="emp2"></entry>
<entry key="2" value-ref="emp2"></entry>
</map>
</property>
<!-- 给属性集合配置 -->
<property name="pp">
<props>
<prop key="pp1">abcd</prop>
<prop key="pp2">hello</prop>
</props>
</property>
</bean>
<bean id="emp1" class="com.litao.collection.Employee">
<property name="name" value="北京" />
<property name="id" value="1" />
</bean>
<bean id="emp2" class="com.litao.collection.Employee">
<property name="name" value="天津" />
<property name="id" value="2" />
</bean>
</beans>
/******************************com.litao.constructor包************************************************/
App1.java
package com.litao.constructor; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class App1 { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ac = new ClassPathXmlApplicationContext("com/litao/constructor/beans.xml"); Employee ee = (Employee)ac.getBean("employee");
System.out.println(ee.getName());
} }
Employee.java
package com.litao.constructor;
public class Employee {
	private String name;
	private int age;
	public Employee() {
	}
	public Employee(String name, int age) {
		System.out.println("Employee(String name, int age)构造函数被调用");
		this.name = name;
		this.age = age;
	}
	public Employee(String name) {
		System.out.println("Employee(String name)构造函数被调用");
		this.name = name;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}
beans.xml
<?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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <!-- 配置一个雇员对象 -->
<bean id="employee" class="com.litao.constructor.Employee">
<!-- 通过构造函数来注入属性值 index代表第几个参数,type是类型 -->
<constructor-arg index="0" type="java.lang.String" value="大明"/>
<constructor-arg index="1" type="int" value="23"/>
</bean>
</beans>
/******************************com.litao.dispatch包************************************************/
App1.java
package com.litao.dispatch; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class App1 { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ac = new ClassPathXmlApplicationContext("com/litao/dispatch/beans.xml"); DBUtil dbUtil = (DBUtil)ac.getBean("dbutil2");
System.out.println(dbUtil.getDrivername()+" "+ dbUtil.getPwd()); } }
DBUtil.java
package com.litao.dispatch;
public class DBUtil {
	private String drivername;
	private String url;
	private String name;
	private String pwd;
	public String getDrivername() {
		return drivername;
	}
	public void setDrivername(String drivername) {
		this.drivername = drivername;
	}
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
}
beans.xml
<?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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <!-- 引入我们的db.properties文件 -->
<context:property-placeholder location="classpath:com/litao/dispatch/db.properties,classpath:com/litao/dispatch/db2.properties"/>
<!-- 配置一个DButil对象 -->
<bean id="dbutil" class="com.litao.dispatch.DBUtil">
<property name="name" value="${name}" />
<property name="drivername" value="${drivername}" />
<property name="url" value="${url}" />
<property name="pwd" value="${pwd}" />
</bean> <!-- 配置一个DButil2对象 -->
<bean id="dbutil2" class="com.litao.dispatch.DBUtil">
<property name="name" value="${db2.name}" />
<property name="drivername" value="${db2.drivername}" />
<property name="url" value="${db2.url}" />
<property name="pwd" value="${db2.pwd}" />
</bean>
</beans>
db.properties
name=scott
drivername=oracle:jdbc:driver:OracleDriver
url=jdbc:oracle:thin:@127.0.0.1:1521:hsp
pwd=tiger
#key=value
db.properties2
db2.name=scott3
db2.drivername=oracle:jdbc:driver:OracleDriver3
db2.url=jdbc:oracle:thin:@127.0.0.1:1521:hsp3
db2.pwd=tiger3 #key=value
/******************************com.litao.inherit包************************************************/
App1.java
package com.litao.inherit; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class App1 { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub ApplicationContext ac = new ClassPathXmlApplicationContext("com/litao/inherit/beans.xml"); Graduate graduate = (Graduate)ac.getBean("graduate");
System.out.println(graduate.getName() + " " + graduate.getAge() + " " + graduate.getDegree()); } }
Graduate.java
package com.litao.inherit;
public class Graduate extends Student {
	private String degree;
	public String getDegree() {
		return degree;
	}
	public void setDegree(String degree) {
		this.degree = degree;
	}
}
Student.java
package com.litao.inherit;
public class Student {
	protected String name;
	protected String age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
}
beans.xml
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <!-- 配置一个学生对象 -->
<bean id="student" class="com.litao.inherit.Student">
<property name="name" value=" 李涛" />
<property name="age" value="30" />
</bean>
<!-- 配置一个Graduate对象 -->
<bean id="graduate" parent="student" class="com.litao.inherit.Graduate">
<!-- 如果自己配置属性name,age,则会替换从父对象集成的数据 -->
<property name="name" value="小明" />
<property name="degree" value="学士" />
</bean>
</beans>
Spring框架学习之第8节的更多相关文章
- Spring框架学习之第2节
		
传统的方法和使用spring的方法 使用spring,没有new对象,我们把创建对象的任务交给了spring的框架,通过配置用时get一下就行. 项目结构 applicationContext.xml ...
 - Spring框架学习之第1节
		
spring快速入门 ① spring是什么? Struts是web框架(jsp/action/actionform) hibernate是orm框架(对象和关系映射框架),处于持久层 sprin ...
 - Spring框架学习之第9节
		
aop编程 aop(aspect oriented programming)面向切面(方面)编程,是所有对象或者是一类对象编程,核心是(在不增加代码的基础上,还增加新功能) 汇编(伪机器指令 mov ...
 - Spring框架学习之第3节
		
model层(业务层+dao层+持久层) spring开发提倡接口编程,配合di技术可以更好的达到层与层之间的解耦 举例: 现在我们体验一下spring的di配合接口编程,完成一个字母大小写转换的案例 ...
 - Spring框架学习之第7节
		
配置Bean的细节 ☞尽量使用scope=”singleton”,不要使用prototype,因为这样对我们的性能影响较大 ②如何给集合类型注入值 Java中主要的map,set,list / 数组 ...
 - Spring框架学习之第6节
		
bean的生命周期 为什么总是一个生命当做一个重点? Servlet –> servlet生命周期 Java对象生命周期 往往笔试,面试总喜欢问生命周期的问题? ① 实例化(当我们的程序加载 ...
 - Spring框架学习之第5节
		
request session global-session 三个在web开发中才有意义 如果配置成prototype有点类似于request 如果配置成singleton有点类似于web开发中的gl ...
 - Spring框架学习之第4节
		
从ApplicaionContext应用上下文容器中获取bean和从bean工厂容器中有什么区别: 具体案例如下 结论: 1.如果使用上下文ApplicationContext,则配置的bean如果是 ...
 - Spring框架学习一
		
Spring框架学习,转自http://blog.csdn.net/lishuangzhe7047/article/details/20740209 Spring框架学习(一) 1.什么是Spring ...
 
随机推荐
- 使用cronolog切割tomcat catalina.out文件
			
今天查看之前配置的tomcat发现catalina.out文件已经增大到接近5G,过不了多久就会将所在分区撑爆. 搜集了一下,大部分都使用cronolog切割catalina.out文件.按照这个方式 ...
 - 遗传学详解及Matlab算法实现
			
遗传学算法概述 从之前转载的博客<非常好的理解遗传算法的例子>中可以知道,遗传学算法主要有6个步骤: 1. 个体编码 2. 初始群体 3. 适应度计算 4. 选择运算 5. 交叉运算 6. ...
 - UVALive - 7374 Racing Gems 二维非递减子序列
			
题目链接: http://acm.hust.edu.cn/vjudge/problem/356795 Racing Gems Time Limit: 3000MS 问题描述 You are playi ...
 - Posix线程编程指南(5) 杂项
			
在Posix线程规范中还有几个辅助函数难以归类,暂且称其为杂项函数,主要包括pthread_self().pthread_equal()和pthread_once()三个,另外还有一个LinuxThr ...
 - ASP.NET MVC 如何在一个同步方法(非async)方法中等待async方法
			
问题 首先,在ASP.NET MVC 环境下对async返回的Task执行Wait()会导致线程死锁.例: public ActionResult Asv2() { //dead lock var t ...
 - 服务器NPC的ID如何分配的
			
服务器ID分配包括NPC,Monster,Pet的ID分配都是调用allocateUID然后自动保存的ID加一,pet说是通过玩家的ID移位获得的,调试一下发现还是调用allocateUID,如果通过 ...
 - PHP soap Web Service 使用SoapDiscovery.class.php 生成wsdl文件
			
PHP soap web service 使用wsdl文件 demo: ============================================================== 服 ...
 - Effeckt.css项目:CSS交互动画应用集锦
			
目前,网上有大量基于CSS转换的实验和示例,但它们都过于分散,而Effeckt.css的目标就是把所有基于CSS/jQuery动画的应用集中起来,例如:弹窗.按钮.导航.列表.页面切换等等. Effe ...
 - ASP.NET MVC 从IHttp到页面输出
			
MVCHandler应该算是MVC真正开始的地方.MVCHandler实现了IHttpHandler接口,ProcessRequest便是方法入口. MVCHandler : IHttpHandler ...
 - HDU4916 Count on the path(树dp??)
			
这道题的题意其实有点略晦涩,定义f(a,b)为 minimum of vertices not on the path between vertices a and b. 其实它加一个minimum ...