Bean
- Bean的配置项
- Bean的作用域
- Bean的生命周期
- Bean的自动装配
- Resources&ResourceLoader
Bean的配置项
- Id 整个IOC容器中的唯一标识
- Class 具体要实例化的哪一个类
- Scope 范围,作用域
- Constructor arguments 构造器的参数,构造器注入会用到
- Properties 属性,设值注入会用到
- Autowiring mode 自动装配的模式
- lazy-initializzation mode 懒加载模式
- Initialization/destruction method 初始化和销毁的方法
在配置是,理论上讲,除了Class以外,其他都是可以不配置的,但是如果我们想从 Bean容器中得到某一实例,有两种方式:
1 根据Id获取 2 根据类型来获取
Bean的作用域
- singleton:单例,指一个Bean容器中只存一份,不指定默认为单例
- prototype:每次请求(每次使用)创建新的实例,destroy方式不生效
- request:每次http请求创建一个实例且仅在当前request内有效
- session:同上,每次http请求创建,当前session内有效
- global session:基于portlet的web中有效(portlet定义了global session),如果是在web中,同session
例子(singleton与prototype)
<?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">
<!--<bean id="beanscope" class="com.torey.bean.BeanScope" scope="singleton"/>-->
<bean id="beanscope" class="com.torey.bean.BeanScope" scope="prototype"/>
</beans>
Bean的生命周期
- 生命周期
– 定义
– 初始化
– 使用
– 销毁
Bean定义:就是在spring的配置文件xml文件中配置的bean,指定bean的id和class
Bean初始化:就是使用 new ClassPathXmlApplicationContext(“spring-xxx.xml”) 初始化,生成bean的实例
Bean的使用:就是在项目中或者单元测试中取出一个bean的实例,并调用它的方法
Bean的销毁:就是在Bean容器停止的时候,去销毁由当前bean创建所有的实例
单个类Bean的初始化
Bean的初始化一般有两种方式:
- Bean初始化1 实现org.springframework.beans.factory.InitializingBean接口
- Bean初始化2 配置init-method
单个类Bean的销毁
Bean的销毁有两种方式:
- Bean销毁1 实现org.springframework.beans.factory.DisposableBean接口
- Bean销毁2 配置destroy-method
示例源码
<?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">
<bean id="beanLifeTest" class="com.torey.bean.BeanLifeTest"
init-method="init" destroy-method="dispo"/>
<bean id="beanLifeTest2" class="com.torey.bean.BeanLiftIntefalseTest"/>
</beans>
BeanLifeTest .java
package com.torey.bean;
/**
* @ClassName:BeanLifeTest
* @Description:
* @author: Torey
*/
public class BeanLifeTest {
public void init(){
System.out.println(this.getClass().getName()+"spring初始化时调用");
}
public void dispo(){
System.out.println(this.getClass().getName()+"spring销毁时调用");
}
}
BeanLiftIntefalseTest .java
package com.torey.bean;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
/**
* @ClassName:BeanLiftTest2
* @Description:
* @author: Torey
*/
public class BeanLiftIntefalseTest implements InitializingBean,DisposableBean {
@Override
public void afterPropertiesSet() throws Exception {
System.out.println(this.getClass().getName()+"spring初始化时调用");
}
@Override
public void destroy() throws Exception {
System.out.println(this.getClass().getName()+"spring销毁时调用");
}
}
配置全局默认初始化、销毁方法
default-init-method default-destroy-method
<?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="destory">
</beans>
Bean装配之Aware接口
Aware
- Spring中提供了一些以Aware结尾的接口,实现了Aware接口的bean在被初始化之后,可以获取响应资源
例如:BeanNameAware就可以获取Bean 的name相关 - 通过Aware接口,可以对Spring响应资源进行操作(一定要慎重)
- 为对Spring进行简单的扩展提供了方便的入口
ApplicationContextAware
作用:它会向实现了这个接口的Bean提供ApplicationContext上下文的信息,注意:该类也需要被spring容器管理才可以
BeanNameAware
作用:BeanNameAware就可以获取Bean 的name相关
ApplicationContextAware及BeanNameAware 例子源码:
package com.torey.aware;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* @ClassName:MoocBeanName
* @Description:
* @author: Torey
*/
public class MoocBeanName implements BeanNameAware,ApplicationContextAware {
private String beanName;
@Override
public void setBeanName(String name) {
this.beanName=name;
System.out.println(this.getClass().getName()+" setBeanName方法:"+name);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
System.out.println("setApplicationContext="+applicationContext.getBean(this.beanName).hashCode());
}
}
<?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">
<!--<bean id="moocApplicationContext" class="com.torey.aware.MoocApplicationContext"/>-->
<bean id="moocBeanName" class="com.torey.aware.MoocBeanName"/>
</beans>
UnitTestBese.java
package com.torey.springtest.base;
import org.junit.After;
import org.junit.Before;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.util.StringUtils;
/**
* @ClassName:UnitTestBase
* @Description:
* @author: Torey
*/
public class UnitTestBase {
public UnitTestBase(){}
private String springXmlPath;
private ClassPathXmlApplicationContext applicationContext;
public UnitTestBase(String springXmlpath){
this.springXmlPath=springXmlpath;
}
@Before
public void before(){
if (StringUtils.isEmpty(springXmlPath)) {
springXmlPath="classpath*:spring-*.xml";
}
applicationContext= new ClassPathXmlApplicationContext(springXmlPath.split("[,\\s]"));
applicationContext.start();
}
@After
public void after(){
applicationContext.destroy();
}
public Object getBean(String beanId){
return applicationContext.getBean(beanId);
}
}
package com.torey.springtest.bean;
import com.torey.springtest.base.UnitTestBase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
/**
* @ClassName:TestAware
* @Description:
* @author: Torey
*/
@RunWith(BlockJUnit4ClassRunner.class)
public class TestAware extends UnitTestBase {
public TestAware(){
super("classpath:spring-aware.xml");
}
@Test
public void testApplication(){
System.out.println("testApplication="+super.getBean("moocBeanName").hashCode());
}
}
Bean的自动装配Autowiring
Bean的自动装配类型:
- No:不做任何操作
- byname: 根据属性名自动装配。此选项将检查容器并根据名字查找与属性完全一致的bean,并将其与属性自动装配
- byType:如果容器中存在一个与指定属性类型相同的bean,那么将与该属性自动装配;如果存在多个该类型bean,那么抛出异常,并指出不能使用byType方式进行装配;如果没有找到相匹配的bean,则什么都不方式
- Constructor:与byType方式类似,不同之处在于它应用于构造器参数。如果容器中没有找到与构造器参数类型一致的bean,那么抛出异常
例子
** spring-autowining.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.xsd">
<bean id="autoWiringService" class="com.torey.autowiring.AutoWiringService"/>
<bean class="com.torey.autowiring.AutoWiringDAO"/>
</beans>
package com.torey.autowiring;
/**
* @ClassName:AutoWiringDAO
* @Description:
* @author: Torey
*/
public class AutoWiringDAO {
public void say(String word){
System.out.println("AutoWiringDAO say方法:" + word);
}
}
package com.torey.autowiring;
/**
* @ClassName:AutoWiringService
* @Description:
* @author: Torey
*/
public class AutoWiringService {
private AutoWiringDAO autoWiringDAO11;
public AutoWiringService(){}
public AutoWiringService(AutoWiringDAO autoWiringDAO11){
this.autoWiringDAO11=autoWiringDAO11;
}
public void say(){
autoWiringDAO11.say("dddd");
}
}
Resources&ResourceLoader
- 针对于资源文件的统一接口
- Resources
- UrlResource:URL对应的资源,根据一个URL地址即可构建
- ClassPathResource:获取类路径下的资源文件
- FileSystemResource: 获取文件系统里面的资源
- ServletContextResource:ServletContext封装的资源,用于访问ServletContext环境下的资源
- InputStreamResource:针对于输入流封装的资源
- ByteArrayResource:针对于字节数组封装的资源
- ResourceLoader:是针对resource进行加载的一个类,在spring的IOC容器中,所有的ApplicationContext都实现了ResourceLoader接口
public interface ResourceLoader(){
Resource getResource(String location);
}
Resource的前缀有如下几种类型:
Prefix | Example | Example |
---|---|---|
classpath: | classpath:com/myapp/config.xml | 从classpath去加载 |
file | file:/data/config.xml | 从文件系统中加载 |
http: | http://myserver/logo.png | 作为一个URL加载 |
(none) | /data/config.xml | 直接输入一个路径 |
ResourceLoader和Resource例子
package com.torey.resource;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.Resource;
import java.io.IOException;
/**
* @ClassName:ToreyResource
* @Description:
* @author: Torey
*/
public class ToreyResource implements ApplicationContextAware {
private ApplicationContext ctx;
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.ctx=applicationContext;
}
public void resource() throws IOException {
Resource classpathResource = ctx.getResource("classpath:config.txt");
System.out.println("classpathResource:"+classpathResource.getFilename());
System.out.println("classpathResource:"+classpathResource.contentLength());
//当没有前缀的时候,是依赖于ApplicationContext,因为ctx是classpath前缀创建的,所以这里也相当于
//classpath:config.txt
Resource resource = ctx.getResource("config.txt");
System.out.println("resource:"+resource.getFilename());
System.out.println("resource:"+resource.contentLength());
Resource fileResource =
ctx.getResource("file:D:\\workspace-idea\\springTest\\spring-test\\src\\main\\resourcess\\config.txt");
System.out.println("fileResource:"+fileResource.getFilename());
System.out.println("fileResource:"+fileResource.contentLength());
Resource urlResource =
ctx.getResource("url:https://www.baidu.com");
System.out.println("urlResource:"+urlResource.getFilename());
System.out.println("urlResource:"+urlResource.contentLength());
}
}
spring-resource.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.xsd">
<bean id="toreyResource" class="com.torey.resource.ToreyResource"/>
</beans>
package com.torey.springtest.bean;
import com.torey.resource.ToreyResource;
import com.torey.springtest.base.UnitTestBase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import java.io.IOException;
/**
* @ClassName:TestResource
* @Description:
* @author: Torey
*/
@RunWith(BlockJUnit4ClassRunner.class)
public class TestResource extends UnitTestBase {
public TestResource(){
super("classpath:spring-resource.xml");
}
@Test
public void testResource(){
ToreyResource toreyResource=(ToreyResource)super.getBean("toreyResource");
try {
toreyResource.resource();
} catch (IOException e) {
e.printStackTrace();
}
}
}
程序运行结果:
根据慕课网 moocer老师的spring课程 整理