学习笔记-Spring入门(二)

本文详细介绍了Spring框架中Bean的基本配置项及其作用域、生命周期,并探讨了Bean的自动装配方式。此外还讨论了如何利用Spring提供的Aware接口来获取框架资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

六、Bean
1、Bean的配置项
Id: 整个IOC容器中该bean的唯一标识
Class: 具体实例化的类
Scope: 范围(作用域)
Constructor arguments:构造器的参数
Properties: 属性
Autowriring mode: 自动装配的格式
lazy-initialization mode:
Initialization/destruction method:初始化和销毁的方法

2、Bean的作用域
singleton:单例,指一个Bean容器中指存在一份。
案例:配置(已知已存在一个类beanScope)

<bean id="beanScope" class="对应类的路径.beanScope" scope="beanScope"></bean>

prototype:每次请求(每次使用)创建新的实例,destory方法不生效。

<bean id="beanScope" class="对应类的路径.beanScope" scope="prototype"></bean>

request:每次http请求创建一个实例且仅在当前request内有效。
session:同上,每次http请求创建,当前session内有效。
global session:基于portlet的web中有效(portlet定义了global session),如果是在web中,同session。(从一个系统通过链接跳到另一个系统,这个时候使用到global session)

3、Bean的生命周期
(1) bean定义
(2) 初始化

  • 实现org.springframework.beans.factory.InitializingBean接口,覆盖afterPropertiesSet方法
public class ExampleBean implements InitializingBean{
    @Override
    public void afterPropertiesSet()throws Exception{
    }
}


- 配置init-method

<bean id="exampleInitBean" class="类路径" init-method=“init”/>
public class ExampleBean{
    public void init(){
    }
}

(3)使用
(4) 销毁

  • 实现org.springframework.beans.factory.DisposableBean接口,覆盖destory方法
public class ExampleBean implements DisposableBean{
    @Override
    public void destory()throws Exception{
    }
}
  • 配置init-method
<bean id="exampleInitBean" class="类路径" destory-method=“cleanup”/>
public class ExampleBean{
    public void cleanup(){
    }
}
  • 配置全局默认的初始化、销毁方法
<?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"
           default-init-method="init" default-destory-method="destory"> 
</beans> 

注:当三种方式同时使用时,调用顺序是:先执行初始化和接口,而默认的方法会不生效。
配置了默认,但是没有实现方法,编译不会报错,但是配置了初始化,不实现方法,编译会报错。
4、Bean的自动装配
4.1 Aware
Spring中提供了一些以Aware结尾的接口,实现了Aware接口的bean在被初始化之后,可以获取相应的资源。
通过Aware接口,可以对Spring相应资源进行操作(一定慎用)
为对Spring进行简单的扩展提供了方便的入口。
5、Resourse&ResourseLoader

(未完待续)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值