Spring的开发配置与Spring中bean的实例化

2014-11-24 07:23:22 · 作者: · 浏览: 0

Spring
1. 三种实例化bean的方法
1) 第一种是使用类构造器实例化;
[html]


2) 第二种是使用静态工厂方法实例化;
[html]
y-method="createPersonServiceBean">


3) 第三种是使用实例工厂方法实例化;
[html]


2. bean的作用域,默认的情况之下,spring容器的bean的作用域是单实例的,也就是说当我们从容器中得到的bean实例是同一个。可以使用scope标签设置bean的作用域为原型,也就是说每次得到的bean是不同的对象实例。scope="prototype"。注意默认情况下的bean是在spring容器实例化的时候就进行实例化的;当是原型时bean的实例化是在getbean的时候进行实例化的。也可以在xml中配置bean的加载时机为延迟。
3. spring的依赖注入之使用属性setter方法实现注入:ref标签或者使用内部bean
1)
[html]

init-method="init"destroy-method="destory">


2)
[html]
init-method="init"destroy-method="destory">




配置xml实现spring注入Set和Map等集合类型。
[html]


第一个
第二个
第三个












4. 使用构造器实现注入
5. 使用注解进行注入
6. 使用注解将bean添加到spring的管理中。
在xml中配置:
[html]
< xml version="1.0"encoding="UTF-8" >
http://www.springframework.org/schema/beans"
xmlnsxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-2.5.xsd">



这样spring容器会在启动时将在指定的包的目录下进行查询查到所有相关的bean对其进行加载和注入。
在相应的需要加载的bean定义的前面添加注解进行标识。
[java]
//使用注解将bean添加到spring容器的管理中
@Service @Scope("prototype")
public class PersonDaoBean implements PersonDao {
//利用注解实现对象初始化操作
@PostConstruct
public void init(){
System.out.println("initinvoked");
}
public void add(){
System.out.println("add methodis invoked!");
}

}

摘自 liuchangqing123