Spring框架下Bean的方法注入(Method injection)

2024-05-01 21:58

本文主要是介绍Spring框架下Bean的方法注入(Method injection),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

通常情况下我们在spring中定义的常用bean都是单例模式(singleton)的例如@Service、@Controller定义的bean,任何一个类都只有一个对象,只进行一次初始化这些类的属性永远是最后一次调用它时的值。但是针对不同的业务场景我们可能会定义一些bean,这些bean的属性在不同场景下它的属性值是不同的,因此这时候我们就不能使用单例模式了而使用原型模式(prototype),这种模式相当于new一个对象。参见spring官方文档。
1.4.6. Method injection
In most application scenarios, most beans in the container are singletons. When a singleton bean needs to collaborate with another singleton bean, or a non-singleton bean needs to collaborate with another non-singleton bean, you typically handle the dependency by defining one bean as a property of the other. A problem arises when the bean lifecycles are different. Suppose singleton bean A needs to use non-singleton (prototype) bean B, perhaps on each method invocation on A. The container only creates the singleton bean A once, and thus only gets one opportunity to set the properties. The container cannot provide bean A with a new instance of bean B every time one is needed.
最后两句:假定有单例bean A和原型bean B,当A初始化的时候只有一次机会初始化B,但是A中可能在不同方法中对B进行了调用,这时候可能B中的部分属性发生了变化,而在A中的不同方法可能希望B中的属性是刚初始化时的值,但是容器并不能提供新的B类的实体,因此才有了下面的解决办法

A solution is to forego some inversion of control. You can make bean A aware of the container by implementing the ApplicationContextAware interface, and by making a getBean(“B”) call to the container ask for (a typically new) bean B instance every time bean A needs it. The following is an example of this approach:

利用ApplicationContextAware接口中的getBean方法向容器请求一个新的bean
具体参考以下代码

package com.spring.util;import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;/*** @author chengjian* @date 2018/5/16**/
@Component
public class SpringBeanFactory implements ApplicationContextAware {private  ApplicationContext applicationContext;@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {this.applicationContext=applicationContext;}public <T> T getBean(Class<T> clazz){try{return applicationContext.getBean(clazz);}catch (Exception e){e.printStackTrace();}return null;}
}

我们创建了一个SpringBeanFactory,这个类实现了ApplicationContextAware方法,我们在类中新定义了一个基于泛型的getBean方法,通过这样的方式我们就能通过方法的方式从spring容器中获取到我们想要的bean。参考下面的代码

package com.spring.javatest.io;import com.github.javafaker.Faker;
import com.spring.config.SpringConfig;
import com.spring.javatest.entity.UserEntity;
import com.spring.util.CommonUtil;
import com.spring.util.SpringBeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.Locale;/*** @author chengjian* @date 2018/5/15**/
@Component
public class OutPutStreamTest {@Autowiredprivate SpringBeanFactory springBeanFactory;public void fileOutPutSerializable() {try {Faker faker=new Faker(new Locale("zh-CN"));UserEntity user=new UserEntity();user.setUserid(CommonUtil.getUuid());user.setUserpwd("123456");user.setUsername("a001");user.setRealname(faker.name().fullName());String fileName = springBeanFactory.getBean(SpringConfig.class).getLocation() + "output";FileOutputStream f = new FileOutputStream(fileName);ObjectOutput s = new ObjectOutputStream(f);s.writeObject(user);s.flush();s.close();f.close();} catch (IOException e) {e.printStackTrace();}}
}

我们并没有通过@Autowired注解注入SpringConfig,而是通过方法注入的方式注入的bean

这篇关于Spring框架下Bean的方法注入(Method injection)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

java如何解压zip压缩包

《java如何解压zip压缩包》:本文主要介绍java如何解压zip压缩包问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Java解压zip压缩包实例代码结果如下总结java解压zip压缩包坐在旁边的小伙伴问我怎么用 java 将服务器上的压缩文件解压出来,

SpringBoot中SM2公钥加密、私钥解密的实现示例详解

《SpringBoot中SM2公钥加密、私钥解密的实现示例详解》本文介绍了如何在SpringBoot项目中实现SM2公钥加密和私钥解密的功能,通过使用Hutool库和BouncyCastle依赖,简化... 目录一、前言1、加密信息(示例)2、加密结果(示例)二、实现代码1、yml文件配置2、创建SM2工具

Spring WebFlux 与 WebClient 使用指南及最佳实践

《SpringWebFlux与WebClient使用指南及最佳实践》WebClient是SpringWebFlux模块提供的非阻塞、响应式HTTP客户端,基于ProjectReactor实现,... 目录Spring WebFlux 与 WebClient 使用指南1. WebClient 概述2. 核心依

SQL Server配置管理器无法打开的四种解决方法

《SQLServer配置管理器无法打开的四种解决方法》本文总结了SQLServer配置管理器无法打开的四种解决方法,文中通过图文示例介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的... 目录方法一:桌面图标进入方法二:运行窗口进入检查版本号对照表php方法三:查找文件路径方法四:检查 S

MyBatis-Plus 中 nested() 与 and() 方法详解(最佳实践场景)

《MyBatis-Plus中nested()与and()方法详解(最佳实践场景)》在MyBatis-Plus的条件构造器中,nested()和and()都是用于构建复杂查询条件的关键方法,但... 目录MyBATis-Plus 中nested()与and()方法详解一、核心区别对比二、方法详解1.and()

Spring Boot @RestControllerAdvice全局异常处理最佳实践

《SpringBoot@RestControllerAdvice全局异常处理最佳实践》本文详解SpringBoot中通过@RestControllerAdvice实现全局异常处理,强调代码复用、统... 目录前言一、为什么要使用全局异常处理?二、核心注解解析1. @RestControllerAdvice2

Spring IoC 容器的使用详解(最新整理)

《SpringIoC容器的使用详解(最新整理)》文章介绍了Spring框架中的应用分层思想与IoC容器原理,通过分层解耦业务逻辑、数据访问等模块,IoC容器利用@Component注解管理Bean... 目录1. 应用分层2. IoC 的介绍3. IoC 容器的使用3.1. bean 的存储3.2. 方法注

golang中reflect包的常用方法

《golang中reflect包的常用方法》Go反射reflect包提供类型和值方法,用于获取类型信息、访问字段、调用方法等,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值... 目录reflect包方法总结类型 (Type) 方法值 (Value) 方法reflect包方法总结

Spring事务传播机制最佳实践

《Spring事务传播机制最佳实践》Spring的事务传播机制为我们提供了优雅的解决方案,本文将带您深入理解这一机制,掌握不同场景下的最佳实践,感兴趣的朋友一起看看吧... 目录1. 什么是事务传播行为2. Spring支持的七种事务传播行为2.1 REQUIRED(默认)2.2 SUPPORTS2

C# 比较两个list 之间元素差异的常用方法

《C#比较两个list之间元素差异的常用方法》:本文主要介绍C#比较两个list之间元素差异,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1. 使用Except方法2. 使用Except的逆操作3. 使用LINQ的Join,GroupJoin