1. Bean的配置
Spring 的IoC容器管理一个或多个Bean,这些Bean由容器根据XML文件中提供的Bean配置信息进行创建。
XML 配置文件的根元素是<beans>,<beans>包含了多个<bean>子元素,每个<bean>子元素定义了一个Bean,并描述了该Bean如何装配到Spring容器中。
一个Bean通常包括id、name和class3个属性
- id:是一个Bean的唯一标识符,容器对Bean的配置、管理都通过该属性来完成。
-name:可以在name属性中为Bean指定多个名称,每个名称之间用逗号或者是分号隔开。
-class:该属性指定了Bean的具体实现类,他必须是一个完整的类型,使用类的全限定名。
2. 注入集合值
对于注入集合值,个人感觉比较 简单,就只贴一些代码进行观察了。
package com.deciphering.InjectCollections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class InjectCollections {
private Set<String> sets;
private List<String> lists;
private Map<String , String> maps;
public Set<String> getSets() {
return sets;
}
public void setSets(Set<String> sets) {
this.sets = sets;
}
public List<String> getLists() {
return lists;
}
public void setLists(List<String> lists) {
this.lists = lists;
}
public Map<String, String> getMaps() {
return maps;
}
public void setMaps(Map<String, String> maps) {
this.maps = maps;
}
@Override
public String toString() {
return "sets " + sets.toString() + "\nlists " + lists.toString() + "\nmaps " + maps.toString() ;
}
public static void main(String[] args){
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
InjectCollections ic= (InjectCollections)ctx.getBean("InjectCollections");
System.out.println(ic);
}
}
根据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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="InjectCollections" class="com.deciphering.InjectCollections.InjectCollections">
<property name="sets">
<set>
<value>1</value>
<value>2</value>
</set>
</property>
<property name="lists">
<list>
<value>1</value>
<value>2</value>
<value>3</value>
</list>
</property>
<property name="maps">
<map>
<entry key="1" value="1"></entry>
<entry key="2" value="2"></entry>
<entry key="3" value="3"></entry>
<entry key="4" value="4"></entry>
</map>
</property>
</bean>
</beans>
好了,这就是集合属性的注入了,比较简单,就不做介绍了。
3. 管理Bean的生命周期
Spring可以管理singleton(单例)作用域Bean的生命周期,Spring可以非常精确的知道周期变化。
但是,对于prototype(多态)作用域的Bean,则是完全由客户端进行托管,Spring不参与。
管理Bean的生命周期重点在于在某个Bean生命周期的某些指定时刻接受通知。这样能够允许你的Bean在其存活期间的指定时刻完成一些相关操作。这样的时刻可能很多,但是有两个时刻确实非常重要的,postinitiation(初始化后)和predestruction(销毁前)。
4.Spring容器中Bean的作用域
在讨论了Bean的生命周期之后,再来介绍Spring容器中Bean的作用域。
- Singleton:单例模式,使用singleton定义的Bean在Spring容器中将只有一个实例,也就是说,无论多少个Bean引用它,始终指向的是同一个对象。
- Prototype:原型模式,每次通过Spring容器获取prototype定义的Bean时,容器都会创建一个新的Bean实例。
- request:针对每一次Http请求都会产生一个新的Bean,而且该Bean仅在当前HTTP request内有效。
- Session:针对每一次Http请求都会产生一个新的Bean,而且该Bean仅在当前HTTP session内有效。
- Global session:类似于标准的Http Session的作用域,但是它仅仅在基于porlet的Web应用中有效。