Bean的配置项
- Id
- Class
- Scope
- Constructor arguments
- Properties
- Autowiring mode
- lazy-initialization mode
- Initialization/destruction method
Bean的作用域
singleton: 单例,指一个Bean容器中只存在一份(默认)
singleton作用域是指在Spring IOC容器中仅存在一个Bean的示例,Bean以单实例的方式存在,单实例模式是重要的设计模式之一,在Spring中对此实现了超越,可以对那些非线程安全的对象采用单实例模式。
prototype:每次请求(每次使用)创建新的实例,destroy方式不生效
在默认情况下,Spring在启动时不实例化prototype的Bean
request:每次http请求创建一个实例且仅在当前request内有效
- session:同上,每次http请求创建,当前session内有效
- global session:基于portlet的web中有效(portlet定义了global session), 如果是在web中,砼session
Bean的生命周期
生命周期
- 定义
- 初始化
- 使用
- 销毁
初始化
- 实现org.springframework.beans.factory.InitializingBean接口,覆盖afterPropertiesSet方法
- 配置init-method
销毁
- 实现org.springframework.beans.factory.DisposableBean,覆盖destroy方法
- 配置destroy-method
以上初始化和销毁只针对单个bean
- 配置全局默认初始化、销毁方法
<?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.xsd
default-init-method="init" default-destroy-method="destroy">
</bean>
如果上述三种方式同时使用了,第三种方式就会失效,第二种先执行,随后是第一种执行。这个时候配置了第三种,没有执行,类中可以不声明默认方法。
Aware接口
- Spring中提供了一些以Aware结尾的接口,实现了Aware接口的bean在被初始化之后,可以获取响应资源
- 通过Aware接口,可以对Spring响应资源进行操作(一定要慎重)
- 为对Spring进行简单的扩展提供了方便的入口
如:
ApplicationContextAware
ApplicationEventPublisherAware
BeanClassLoaderAware
BeanFactoryAware
BeanNameAware
BootstrapContextAware
LoadTimeWeaverAware
MessageSourceAware
NotificationPublisherAware
PortletConfigAware
PortletContextAware
ResourceLoaderAware
ServletConfigAware
ServletContextAware
Bean的自动装配(AutoWiring)
如下四种类型:
- No:不做任何操作
- byName: 根据属性名自动装配。此选项将检查容器并根据名字查找与属性完全一致的bean,并将其与属性自动装配
- byType: 如果容器中存在一个与指定属性类型相同的bean,那么将与该属性自动装配;如果存在多个该类型的bean,那么抛出异常,并指出不能使用byType方式进行自动装配;如果没有找到相匹配的bean,则什么事都不发生
- constructor: 与byType方式类似,不同之处在于它应用于构造器参数。如果容器中没有找到与构造器参数类型一致的bean,那么抛出异常。
- autodetect:
Resources
- 针对资源文件的统一接口
Resources
- UrlResource:URL对应的资源,根据一个URL地址即可构建
- ClassPathResource:获取类路径下的资源文件
- FileSystemResource:获取文件系统里面的资源
- ServletContextResource:ServletContext封装的资源,用于访问ServletContext环境下的资源
- InputStreamResource:针对输入流封装的资源
- ByteArrayResource:针对于字节数组封装的资源
ResourceLoader
对Resource进行加载的一个类。Spring IOC容器中所有的application context都实现了ResourceLoader接口,所以,所有application context都可以用来获取Resource实例。
//接口定义
public interface ResourceLoader {
Resource getResource(String location);
}
//demo
Resource template = ctx.getResource("some/resource/path/myTemplate.txt");
Resource template = ctx.getResource("classpath:some/resource/path/myTemplate.txt");
Resource template = ctx.getResource("file:/some/resource/path/myTemplate.txt");
Resource template = ctx.getResource("url:http://www.xxx.com/some/resource/path/myTemplate.txt");
ResourceLoader的前缀有四种:
- classpath:从classpath下加载
- file:从文件系统中加载
- http:作为URL加载
- (none):什么都没有,依赖于applicationContext