当前位置: 首页 > news >正文

SpringBean

1. 什么是Spring Bean

定义: Spring Bean是由Spring IoC容器管理的对象。是应用程序的核心组成部分,通常是服务、DAO、控制器等。

2. Bean的定义方式

XML配置: 通过XML文件定义Bean。

<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd"><bean id="myBean" class="com.example.MyBean"><property name="property1" value="value1"/><property name="property2" ref="anotherBean"/></bean></beans>

注解配置: 使用@Component@Service@Repository@Controller等注解定义Bean。

import org.springframework.stereotype.Component;@Component
public class MyBean {}
import org.springframework.stereotype.Service;@Service
public class MyService {}
import org.springframework.stereotype.Repository;@Repository
public class MyRepository {}
import org.springframework.stereotype.Controller;@Controller
public class MyController {}

Java配置: 使用@Configuration@Bean注解

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class AppConfig {@Beanpublic MyBean myBean() {return new MyBean();}@Beanpublic AnotherBean anotherBean() {return new AnotherBean();}
}

3.Bean的作用域

Spring Bean的作用域决定了Bean实例的创建和管理方式。

3.1 singleton

默认作用域:整个Spring容器中只有一个实例。

特点:每次注入时,都会返回同一个实例。

适用场景:适用于无状态的Bean,例如服务类、DAO类等。

@Component
@Scope("singleton")
public class MySingletonBean {}
3.2. prototype

每次请求都会创建一个新的实例

特点:每次注入时,都会创建一个新的实例。

适用场景:适用于有状态的Bean,例如需要频繁创建和销毁的对象。

@Component
@Scope("prototype")
public class MyPrototypeBean {}
3.3. request

每个HTTP请求都会创建一个新的实例(仅适用于Web应用)。

特点:在同一个HTTP请求内,Bean是单例的;不同的HTTP请求会创建不同的实例。

适用场景:适用于需要在单个HTTP请求中保持状态的Bean。

@Component
@Scope("request")
public class MyRequestBean {}
3.4. session

每个HTTP会话都会创建一个新的实例(仅适用于Web应用)。

特点:在同一个HTTP会话内,Bean是单例的;不同的HTTP会话会创建不同的实例。

适用场景:适用于需要在用户会话中保持状态的Bean。

@Component
@Scope("session")
public class MySessionBean {}
3.5. globalSession

全局HTTP会话(仅适用于Portlet应用)。

特点:在同一个全局会话内,Bean是单例的;不同的全局会话会创建不同的实例。

适用场景:适用于需要在Portlet应用中跨多个Portlet共享状态的Bean。

@Component
@Scope("globalSession")
public class MyGlobalSessionBean {}

4.Bean的生命周期

Spring Bean的生命周期由Spring IoC容器管理,

这些阶段确保了Bean在整个生命周期中能够正确地初始化和清理资源。

4.1实例化

通过构造函数或工厂方法创建Bean实例。

过程:Spring容器根据Bean定义(XML配置、注解配置或Java配置)创建Bean实例。

public class MyBean {public MyBean() {// 构造函数}
}
4.2. 属性注入

通过setter方法或构造函数注入依赖

过程:Spring容器在实例化Bean后,注入其依赖的属性。

public class MyBean {private AnotherBean anotherBean;// 构造函数注入public MyBean(AnotherBean anotherBean) {this.anotherBean = anotherBean;}// Setter方法注入public void setAnotherBean(AnotherBean anotherBean) {this.anotherBean = anotherBean;}
}
4.3. 初始化

调用@PostConstruct注解的方法或实现InitializingBean接口的afterPropertiesSet方法。

过程:在Bean的属性注入完成后,Spring容器会调用初始化方法进行进一步的设置或初始化操作。

import javax.annotation.PostConstruct;public class MyBean implements InitializingBean {@PostConstructpublic void init() {// 使用@PostConstruct注解的方法System.out.println("Bean is going through init.");}@Overridepublic void afterPropertiesSet() throws Exception {// 实现InitializingBean接口的afterPropertiesSet方法System.out.println("Bean is going through afterPropertiesSet.");}}
3.4. 销毁

调用@PreDestroy注解的方法或实现DisposableBean接口的destroy方法。

过程:在Spring容器关闭或Bean被销毁之前,Spring容器会调用销毁方法进行清理工作。

import javax.annotation.PreDestroy;public class MyBean implements DisposableBean {@PreDestroypublic void destroy() {// 使用@PreDestroy注解的方法System.out.println("Bean will destroy now.");}@Overridepublic void destroy() throws Exception {// 实现DisposableBean接口的destroy方法System.out.println("Bean will destroy now.");}}

5.依赖注入(DI)

依赖注入(Dependency Injection, DI)是Spring框架的核心特性之一,允许对象在创建时将其依赖项注入到对象中,而不是在对象内部自行创建依赖项。

Spring支持三种主要的依赖注入方式:构造函数注入、Setter方法注入和字段注入。

5.1构造函数注入
  • 通过构造函数传递依赖
  • 特点:依赖项在对象创建时通过构造函数传递,确保对象在创建时就具备所有必需的依赖项。
  • 优点:依赖项是不可变的,适合强制依赖的场景。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;@Component
public class MyBean {private final AnotherBean anotherBean;// 构造函数注入@Autowiredpublic MyBean(AnotherBean anotherBean) {this.anotherBean = anotherBean;}// 业务方法public void doSomething() {anotherBean.performTask();}}
5.2 Setter方法注入
  • 通过setter方法传递依赖
  • 特点:依赖项在对象创建后通过setter方法传递,允许在对象创建后再设置或更改依赖项。
  • 优点:灵活性高,适合可选依赖或需要在运行时动态更改依赖的场景。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;@Component
public class MyBean {private AnotherBean anotherBean;// Setter方法注入@Autowiredpublic void setAnotherBean(AnotherBean anotherBean) {this.anotherBean = anotherBean;}// 业务方法public void doSomething() {anotherBean.performTask();}}
5.3 字段注入
  • 通过@Autowired注解直接在字段上注入依赖
  • 特点:依赖项直接注入到字段中,简化了代码,不需要显式的setter方法。
  • 优点:代码简洁,适合简单的依赖注入场景。
  • 缺点:不利于单元测试,因为依赖项是私有的,难以通过反射进行注入。
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;@Component
    public class MyBean {// 字段注入@Autowiredprivate AnotherBean anotherBean;// 业务方法public void doSomething() {anotherBean.performTask();}}


http://www.mrgr.cn/news/14782.html

相关文章:

  • 工业软件架构1:(QT和C++实现)
  • 基于SOA-BP海鸥优化BP神经网络实现数据预测Python实现
  • 使用arthas调用带参数的方法-傻瓜式教程
  • 网络通信特刊合集(二)——Springer特刊推荐
  • ES配合高德地图JS-API实现地理位置查询
  • Gradle下载失败或者慢怎么办
  • 作业0829
  • 如何利用 Go 语言开发高可用服务
  • 第一个go程序
  • 【LeetCode Cookbook(C++ 描述)】平衡二叉树
  • 使用 `free -m` 命令查看 Linux 系统内存状态
  • PWE3简介
  • 基于SSM+小程序的乡村游小程序登录管理系统(旅游3)(源码+sql脚本+视频导入教程+文档)
  • Cmake教程之一(入门Cmake基础命令)
  • pnpm 查看库的所有版本
  • 005-CircuitBreaker断路器-Resilience4J
  • Mozilla为本地音频到文本翻译开发Whisperfile引擎
  • 力扣1442.形成两个异或相等数组的三元组数目
  • Web之tomcat
  • 王立铭脑科学50讲,50、现在和未来,脑机接口能否带来脑的升级