SpringBean

devtools/2024/9/24 6:12:55/

1. 什么是Spring Bean

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

2. Bean的定义方式

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

java"><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。

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

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

java">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类等。

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4.Bean的生命周期

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

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

4.1实例化

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

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

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

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

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

java">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容器会调用初始化方法进行进一步的设置或初始化操作。

java">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容器会调用销毁方法进行清理工作。

java">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构造函数注入
  • 通过构造函数传递依赖
  • 特点:依赖项在对象创建时通过构造函数传递,确保对象在创建时就具备所有必需的依赖项。
  • 优点:依赖项是不可变的,适合强制依赖的场景。
java">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方法传递,允许在对象创建后再设置或更改依赖项。
  • 优点:灵活性高,适合可选依赖或需要在运行时动态更改依赖的场景。
java">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方法。
  • 优点:代码简洁,适合简单的依赖注入场景。
  • 缺点:不利于单元测试,因为依赖项是私有的,难以通过反射进行注入。
    java">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.ppmy.cn/devtools/99696.html

相关文章

Swift 中的影像魔术:Core Video 的高级应用

标题&#xff1a;Swift 中的影像魔术&#xff1a;Core Video 的高级应用 在 Swift 开发中&#xff0c;Core Video 是 Apple 提供的一个强大的框架&#xff0c;用于处理高质量的视频内容。从实时视频滤镜到高级图像处理&#xff0c;Core Video 为开发者提供了丰富的 API 来实现…

链动 2+1 模式小程序 AI 智能名片商城源码培训邀约策略研究

摘要&#xff1a;本文深入剖析链动 21 模式小程序 AI 智能名片商城源码的培训邀约策略&#xff0c;从该源码的价值出发&#xff0c;阐述邀约的重要性&#xff0c;并详细介绍具体的邀约策略&#xff0c;旨在为相关培训活动提供切实可行的指导&#xff0c;提高邀约成功率&#xf…

Git 版本控制操作

1. 版本回退 Git 能够管理⽂件的历史版本&#xff0c;这是版本控制器重要的能⼒。如果有⼀天你发现之前前的⼯作做的出现了很⼤的问题&#xff0c;需要在某个特定的历史版本重新开始&#xff0c;这个时候&#xff0c;就需要版本回退的功能了。 执⾏ git reset 命令⽤于回退版…

6.2 频率域滤波之高通滤波

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 前言1. 理论基础2. 示例分析2.1 示例代码2.2 示例效果分析 前言 上一章我们讲到频率低通滤波&#xff0c;简而言之就是让图像的低频信号通过&#xff0c;过滤或者衰…

微信小程序:点击事件(bindtap)传递参数

小程序在组件上绑定事件后&#xff0c;传递参数的方式不同于前端其他场景中直接加参数的方式&#xff0c;小程序在参数的传递时&#xff0c;采用事件对象的自定义属性的方式&#xff0c;具体实现如下&#xff1a; wxml&#xff1a; <view bindtap"goIndex" data…

True XML cookbook

打开题目 看到登录口 随便输入admin&#xff0c;123456&#xff0c;然后抓包试一下 先按原来那道题的payload进行测试&#xff0c;payload和结果如下&#xff1a; <?xml version"1.0" ?> <!DOCTYPE llw [ <!ENTITY file SYSTEM "file:///flag&…

pycharm修改文件大小限制

场景&#xff1a; 方法&#xff1a; 打开pycharm 安装目录下的idea.properties 增加配置项&#xff1a;idea.max.intellisense.filesize99999

开源模型应用落地-qwen2-7b-instruct-LoRA推理Gradio-Axolotl-单机单卡-V100(十一)

一、前言 本篇文章将使用Axolotl去调用微调后的模型权重,包括使用命令行及Gradio方式,通过阅读本文,您将能够更好地掌握这些关键技术,理解其中的关键技术要点,并应用于自己的项目中。 前置内容:开源模型应用落地-qwen2-7b-instruct-LoRA微调-Axolotl-单机单卡-V100(九)…