SpringBean

2024-08-25 07:44
文章标签 springbean

本文主要是介绍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();}}

这篇关于SpringBean的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1104953

相关文章

Spring:浅谈对SpringBean的认识

一、SpringBean的生命周期 1、实例化bean对象:通过反射的方式进行对象的创建,此时的创建只是在堆空间中申请空间,属性都是默认值。 2、设置对象属性:给对象中的属性进行值的设置工作。 3、检查Aware相关接口并设置相关依赖:如果对象中需要引用容器内部的对象,那么需要调用aware接口的子类方法来进行统一的设置。 4、BeanPostProcessor的前置处理:对生成的bean对象

SpringBean的管理

一、bean的名字与标识符 <bean id="" class=""></bean> bean的名字作用: 获取这个bean通过bean名字获取 bean名字配置方式: id: 唯一标志符, 命名规范与变量命名规范一样, 包含特殊符号name: 配置名字: 可以包含特殊符号,没有要求, 比如. 一次性取多个名字 <bean name="dog1,dog2,dog3" id="dog" c

简单上手SpringBean的整个装配过程

你好,这里是codetrend专栏“Spring6全攻略”。 典型的企业级应用程序并非仅由单个对象(在Spring术语中称为bean)组成。即使是最简单的应用程序,也会包含一些协同工作的对象,共同呈现出终端用户眼中连贯一致的应用程序形态。 以下mermaid流程图简单展示了Spring工作过程。 #mermaid-svg-8n4UYVQi9oQhqjbh {font-family:"tr

SpringBean详解

文章目录 概述Spring获取Bean的流程依赖注入bean的作用域Spring 中的 Bean 是线程安全的吗Spring如何处理线程并发问题bean 的自动装配和方式@Resource和@Autowired的区别bean的自动装配bean的生命周期BeanFactoryBeanFactory 常用的实现类有哪些BeanFactory与FactoryBean的不同ApplicationCo

【Spring篇】三.springBean自动装配及Resources

1. 自动装配(Autowiring) 类型 1.1 No : 不做任何操作1.2 byName : 根据属性名自动装配。根据容器中bean名字查找与属性完全一致的bean,将其自动装配。bean中name重复会报错。 定义dao和service public class TestDao {public void say(String word){System.out.println(

【Spring篇】二.springBean的生命周期及Aware接口

1. 生命周期 1.1 定义 <bean id="student" class="com.wpj.bean.Student"></bean> 1.2 初始化 spring容器在初始化的时候会创建一系列对象,同时将对象之间的依赖关系通过注入方式组织起来方式第一种: 实现org.springframework.beans.factory.InitializingBean接口,覆盖after

【Spring篇】一.spring及springBean的配置

IOC (控制反转) 将控制权交给Spring容器,要使用的时候找spring容器也获取依赖对象 应用程序本身不负责依赖对象的创建和维护,而是由外部容器负责创建和维护 DI (依赖注入) 控制反转的一种实现方式 ioc目的:创建对象且组装对象之间的关系。spring容器在初始化的时候会创建一系列对象,同时将对象之间的依赖关系通过注入方式住址起来 扩展 q:控制反转,哪些方面的控制被反转

【SpringBean】bean的作用域和bean的生命周期

目录 前言 一 bean的作用域 1. singleton——唯一 bean 实例 2. prototype——每次请求都会创建一个新的 bean 实例 3. request——每一次HTTP请求都会产生一个新的bean,该bean仅在当前HTTP request内有效 4. session——每一次HTTP请求都会产生一个新的 bean,该bean仅在当前 HTTP sess

SpringBean生命周期之InitializingBean,初始化bean

1 yml文件 weixin:appid: aaaaaapartner: 12313214partnerkey: ccccccert: C:\\Users\\lenovo\\Desktop 2 Bean初使化 import org.springframework.beans.factory.InitializingBean;import org.springframework.beans.

SpringFramework:SpringBean的注入方式

SpringBean的注入方式 文章目录 SpringBean的注入方式一、Spring 容器1. 什么是容器2. 容器如何工作 二、SpringBean 注入方式1. SpringBean 注入方式分类2. @Autowiring 自动绑定 三、获取 Spring Bean 一、Spring 容器 1. 什么是容器 Spring IOC 容器就是一个 org.sp