Spring Bean作用域Scope(含SpringCloud中的RefreshScope )

@RefreshScope源码解析 RefeshScope这个注解想必大家都用过,在微服务配置中心的场景下经常出现,它可以用来刷新Bean中的属性配置,那么它是如何做到的呢?让我们来一步步揭开它神秘的面纱。就是说我们在修改了bean属性的时候项目不需要重新启动,就可以拿到最新的值。我们先来看下@RefreshScope的接口@Target({/***/ //创建基于类的代理(使用 CGLIB) ScopedProxyMode proxyMode() default ScopedProxyMode . TARGET_CLASS; 阅读详情

前言

本文主要讨论SpringBean的作用域,我们这里讨论的Bean的作用域,很大程度都是默认只讨论依赖来源为【Spring BeanDefinition】的作用域,因为在我们的业务开发中,我们都是Spring框架的使用者,我们自定义的bean几乎全部都是属于【Spring BeanDefinition】的。后续文章以这个为默认前提。

作用域概览

来源

说明

singleton

默认的spring bean作用域,一个BeanFactory有且仅有一个实例,重要

prototype

原型作用域,每一次的依赖查找和依赖注入都会生成新的bean对象,重要

request

将SpringBean存储在ServletRequest上下文中,不重要

session

将SpringBean存储在HttpSession上下文中,不重要

application

将SpringBean存储在ServletContext上下文中,不重要

由于目前的开发模式基本都是前后端分离,以前我们写JSP的时候需要从后端的response对象中获取部分数据进行展示,现在这些模板技术[JSP,Freemarker,Velocity等等]已经边缘化,这里不会重点讨论后三者作用域。

Singleton作用域

首先我们看一下Spring官方文档的描述:
Only one shared instance of a singleton bean is managed, and all requests for beans with an ID or IDs that match that bean definition result in that one specific bean instance being returned by the Spring container.

To put it another way, when you define a bean definition and it is scoped as a singleton, the Spring IoC container creates exactly one instance of the object defined by that bean definition. This single instance is stored in a cache of such singleton beans, and all subsequent requests and references for that named bean return the cached object. The following image shows how the singleton scope works:

Spring’s concept of a singleton bean differs from the singleton pattern as defined in the Gang of Four (GoF) patterns book. The GoF singleton hard-codes the scope of an object such that one and only one instance of a particular class is created per ClassLoader. The scope of the Spring singleton is best described as being per-container and per-bean. This means that, if you define one bean for a particular class in a single Spring container, the Spring container creates one and only one instance of the class defined by that bean definition. The singleton scope is the default scope in Spring. To define a bean as a singleton in XML, you can define a bean as shown in the following example:

<bean id="accountService" class="com.something.DefaultAccountService"/>

<!-- the following is equivalent, though redundant (singleton scope is the default) -->
<bean id="accountService" class="com.something.DefaultAccountService" scope="singleton"/>

核心点已经高亮出来,对Spring来说,Singleton是指在一个容器中,一般是BeanFactory,只存在一个特定ID的Bean。
singleton作用域也是默认的作用域。

Prototype作用域

依然先看一下Spring官方文档的描述:
The non-singleton prototype scope of bean deployment results in the creation of a new bean instance every time a request for that specific bean is made. That is, the bean is injected into another bean or you request it through a getBean() method call on the container. As a rule, you should use the prototype scope for all stateful beans and the singleton scope for stateless beans.
我们应该让所有的有状态bean是prototype scope,让所有的无状态bean是singleton scope。

The following diagram illustrates the Spring prototype scope:

 

(A data access object (DAO) is not typically configured as a prototype, because a typical DAO does not hold any conversational state. It was easier for us to reuse the core of the singleton diagram.)
DAO一般不应该被设置为prototype作用域,因为常规的DAO不应该包含任何会话状态。所以应该配置为singleton作用域。它这里只是举例说明。

The following example defines a bean as a prototype in XML:

<bean id="accountService" class="com.something.DefaultAccountService" scope="prototype"/>

In contrast to the other scopes, Spring does not manage the complete lifecycle of a prototype bean. The container instantiates, configures, and otherwise assembles a prototype object and hands it to the client, with no further record of that prototype instance. Thus, although initialization lifecycle callback methods are called on all objects regardless of scope, in the case of prototypes, configured destruction lifecycle callbacks are not called. The client code must clean up prototype-scoped objects and release expensive resources that the prototype beans hold. To get the Spring container to release resources held by prototype-scoped beans, try using a custom bean post-processor, which holds a reference to beans that need to be cleaned up.
与其他作用域不同,Spring并不管理prototype bean的整个生命周期。容器实例化、配置和以其他方式组装prototype对象并将其交给客户端,而不再记录该prototype实例。

In some respects, the Spring container’s role in regard to a prototype-scoped bean is a replacement for the Java new operator. All lifecycle management past that point must be handled by the client. (For details on the lifecycle of a bean in the Spring container, see Lifecycle Callbacks.)
在某些方面,Spring的prototype作用域是Java里new这种行为的一种替代,这种作用域的生命周期都被客户端控制。生命周期管理请参考Lifecycle Callbacks章节。

点击查看[示例代码]

结论一:
Singleton Bean 无论依赖查找还是依赖注入,均为同一个对象
Prototype Bean 无论依赖查找还是依赖注入,均为新生成的对象

结论二:
如果依赖注入集合类型的对象,Singleton Bean 和 Prototype Bean 均会存在一个于你指定的集合中,
并且该集合里的Prototype Bean和其他地方依赖注入的Prototype Bean是不一样的对象。相当于又生成了一个。

结论三:
无论是 Singleton 还是 Prototype Bean 均会执行初始化方法回调
不过仅 Singleton Bean 会执行销毁方法回调,所以prototype bean的销毁需要客户端自己控制。

未深入研究的作用域

1.Request作用域:作用域为同一个 Http Request。
2.Session作用域:作用域为同一个 Http Session。
3.Application作用域:作用域为同一个WEB容器,可以看做Web应用中的单例模式。
4.WebSocket作用域:作用域为同一个WebSocket应用。
前后端分离后,不重要,暂不记录。

自定义Bean作用域

Spring官方文档有介绍自定义作用域,下例创建了一个作用域为当前线程的作用域:如果在不同的线程中,调用同一个spring容器的依赖查找或者依赖注入某个bean,每个线程都会分别创建一个该bean的示例。

import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;
import org.springframework.core.NamedThreadLocal;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;

import java.util.HashMap;
import java.util.Map;

/**
 * ThreadLocal 级别 Scope
 */
public class ThreadLocalScope implements Scope {

    public static final String SCOPE_NAME = "thread-local";

    private final NamedThreadLocal<Map<String, Object>> threadLocal = new NamedThreadLocal("thread-local-scope") {

        public Map<String, Object> initialValue() {
            return new HashMap<>();
        }
    };

    @Override
    public Object get(String name, ObjectFactory<?> objectFactory) {

        // 非空
        Map<String, Object> context = getContext();

        Object object = context.get(name);

        if (object == null) {
            object = objectFactory.getObject();
            context.put(name, object);
        }

        return object;
    }

    @NonNull
    private Map<String, Object> getContext() {
        return threadLocal.get();
    }

    @Override
    public Object remove(String name) {
        Map<String, Object> context = getContext();
        return context.remove(name);
    }

    @Override
    public void registerDestructionCallback(String name, Runnable callback) {
        // TODO
    }

    @Override
    public Object resolveContextualObject(String key) {
        Map<String, Object> context = getContext();
        return context.get(key);
    }

    @Override
    public String getConversationId() {
        Thread thread = Thread.currentThread();
        return String.valueOf(thread.getId());
    }
}

从Spring官方文档我们学习到要使用一个自定义作用域有2步:
1.创建一个自定义作用域(Creating a Custom Scope),如上面的代码示例,其实只是一个create
2.把你的作用域注册到spring(Using a Custom Scope),让spring容易知道存在这样一个新的scope

将作用域注册到spring容器中,基本的API是:ConfigurableBeanFactory#registerScope

package org.springframework.beans.factory.config;
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
	/**
	 * Register the given scope, backed by the given Scope implementation.
	 * @param scopeName the scope identifier
	 * @param scope the backing Scope implementation
	 */
	void registerScope(String scopeName, Scope scope);
}

下例展示了如何将作用域注册到spring容器中:

public class ThreadLocalScopeDemo {

    @Bean
    @Scope(ThreadLocalScope.SCOPE_NAME) //这里将一个Bean的作用域设置为我们自己的作用域
    public User user() {
        return createUser();
    }

    private static User createUser() {
        User user = new User();
        user.setId(System.nanoTime());
        return user;
    }

    public static void main(String[] args) {

        // 创建 BeanFactory 容器
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        // 注册 Configuration Class(配置类) -> Spring Bean
        applicationContext.register(ThreadLocalScopeDemo.class);

        applicationContext.addBeanFactoryPostProcessor(beanFactory -> {
            // 注册自定义 scope
            beanFactory.registerScope(ThreadLocalScope.SCOPE_NAME, new ThreadLocalScope());
        });
        // 启动 Spring 应用上下文
        applicationContext.refresh();
        //依赖查找
        scopedBeansByLookup(applicationContext);
        // 关闭 Spring 应用上下文
        applicationContext.close();
    }

    private static void scopedBeansByLookup(AnnotationConfigApplicationContext applicationContext) {

        for (int i = 0; i < 3; i++) {
            Thread thread = new Thread(() -> {
                // user在相同线程是共享Bean对象,在不同线程是不同的对象
                User user = applicationContext.getBean("user", User.class);
                System.out.printf("[Thread id :%d] user = %s%n", Thread.currentThread().getId(), user);
            });

            // 启动线程
            thread.start();
            // 强制线程执行完成
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

这样我们就实现了一个例子,把自定义scope的使用说清了,下面我们研究一下这个接口:org.springframework.beans.factory.config.Scope
这可是和BeanDefinition在同一个包中,相当于是SpringIOC的基础核心包。
这个接口从Spring2.0就出现了,接口定义的方法如下:

public interface Scope {
	Object get(String name, ObjectFactory<?> objectFactory);

	@Nullable
	Object remove(String name);

	void registerDestructionCallback(String name, Runnable callback);

	@Nullable
	Object resolveContextualObject(String key);

	@Nullable
	String getConversationId();
}

方法名

说明

get(String name, ObjectFactory<?> objectFactory)

返回一个属于当前自定义Scope的对象

remove(String name)

将一个指定name的对象从当前Scope中移除

registerDestructionCallback(String name, Runnable callback)

注册一个回调,当某个name的对象在当前Scope被销毁时执行。

resolveContextualObject(String key)

解析给定键的上下文对象(如果有)。例如,HttpServletRequest对象的key:"request" ,不太好理解,但是查询调用的地方,发现是
BeanExpressionContext.java在使用,看起来是SpEL表达式(或理解为JSP页面)使用时,用"request"表示servletRequest

getConversationId()

获取一个当前scope的会话id,对上例ThreadLocalScope来说,就是当前线程的线程id

这里需要注意的是:之前我们在学习依赖查找时,比如我们调用applicationContext.getBean(String name)的时候,内部的代码会判断一个bean是singleton还是prototype,也会和我们上述的Scope接口打交道,singleton与prototype是最最基础的2个作用域,它们是通过在org.springframework.beans.factory.config.ConfigurableBeanFactory类中定义了2个常量字符串来表示,而每一个BeanDefinition中的定义都是包含2个方法:boolean isPrototype();与boolean isSingleton();
1.org.springframework.beans.factory.config.ConfigurableBeanFactory#SCOPE_SINGLETON
2.org.springframework.beans.factory.config.ConfigurableBeanFactory#SCOPE_PROTOTYPE

依赖查找最核心的方法:
AbstractBeanFactory.doGetBean(final String name, final Class requiredType, final Object[] args, boolean typeCheckOnly)

	protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
			@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {

		final String beanName = transformedBeanName(name);
		Object bean;

		// Eagerly check singleton cache for manually registered singletons.
		Object sharedInstance = getSingleton(beanName);
		if (sharedInstance != null && args == null) {
			//省略...
		}
		else {
			// Fail if we're already creating this bean instance: We're assumably within a circular reference.
			if (isPrototypeCurrentlyInCreation(beanName)) {
				throw new BeanCurrentlyInCreationException(beanName);
			}

			// Check if bean definition exists in this factory.
			BeanFactory parentBeanFactory = getParentBeanFactory();
			if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
				// 省略。。。
			}

			if (!typeCheckOnly) {
				markBeanAsCreated(beanName);
			}

			try {
				final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
				checkMergedBeanDefinition(mbd, beanName, args);

				// 省略...

				// 判断BeanDefinition是不是单例
				if (mbd.isSingleton()) {
					//省略...单例bean的创建方式
				}

				else if (mbd.isPrototype()) {
                                        //判断BeanDefinition是不是prototype
					//省略...prototype bean的创建方式
				}
				else {
//其他作用域的bean的创建,在这里和Scope接口打交道的
					String scopeName = mbd.getScope();
					final Scope scope = this.scopes.get(scopeName);
					if (scope == null) {
						throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
					}
					try {
//这里调用了Scope.get()
						Object scopedInstance = scope.get(beanName, () -> {
							beforePrototypeCreation(beanName);
							try {
								return createBean(beanName, mbd, args);
							}
							finally {
								afterPrototypeCreation(beanName);
							}
						});
						bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
					}
					catch (IllegalStateException ex) {
						throw new BeanCreationException(beanName,
								"Scope '" + scopeName + "' is not active for the current thread; consider " +
								"defining a scoped proxy for this bean if you intend to refer to it from a singleton",
								ex);
					}
				}
			}
			catch (BeansException ex) {
				cleanupAfterBeanCreationFailure(beanName);
				throw ex;
			}
		}
		// 省略...
	}

所以这里的Scope接口的学习都是为了学习自定义Scope的使用,一般业务代码的编写是不会使用到的,但是在我们新的SpringCloud生态圈中就出现了一个自定义Scope:RefreshScope。

SpringCloud中的RefreshScope

(a)RefreshScope简介
在如下spring模块中引入了一个自定义Scope,叫RefreshScope。基于上面对Scope接口的学习,我们可以认为:@RefreshScope 是scopeName="refresh"的@Scope.

  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-context</artifactId>

SpringCloud context中存在2个RefreshScope.class:

  1. org.springframework.cloud.context.config.annotation.RefreshScope 这是注解,是从Scope注解派生出来的。
  • @RefreshScope等于@Scope("refresh")
  1. org.springframework.cloud.context.scope.refresh.RefreshScope 这是Scope接口(上面介绍过)的实现类。
public class RefreshScope extends GenericScope implements ApplicationContextAware, ApplicationListener<ContextRefreshedEvent>, Ordered {
...
    public RefreshScope() {
        super.setName("refresh");
    }
...
}

(b)RefreshScope实现类的注册
GenericScope注册自己(实现类是RefreshScope)

public class GenericScope implements Scope, BeanFactoryPostProcessor...{
  @Override
  public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
      throws BeansException {
      beanFactory.registerScope(this.name, this); //name=refresh this=RefreshScope对象
      ...
  }
}

(c)@RefreshScope注解修饰的Bean
当Spring容器启动的时候,我们自定义的bean会被注册到IoC容器中,在该过程中:
org.springframework.context.annotation.AnnotatedBeanDefinitionReader#doRegisterBean方法中,会解析我们自定义Bean对象的Scope注解的属性等。

	private <T> void doRegisterBean(Class<T> beanClass, @Nullable String name,
			@Nullable Class<? extends Annotation>[] qualifiers, @Nullable Supplier<T> supplier,
			@Nullable BeanDefinitionCustomizer[] customizers) {

		AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(beanClass);
		if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
			return;
		}

		abd.setInstanceSupplier(supplier);
		ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd); //这里解析Scope注解元信息
		abd.setScope(scopeMetadata.getScopeName());
		String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));

(d)Scope接口的实现类RefreshScope注入到容器的过程
到此,我们还有一个疑问没有解决:
RefreshScope实现类并不是一个Bean,并未被容器管理到,它是怎么被注入到IoC容器中的呢?
答案是:org.springframework.cloud.autoconfigure.RefreshAutoConfiguration
在SpringCloud中,RefreshAutoConfiguration自动装配的时候,会初始化RefreshScope实例。

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(RefreshScope.class)
@ConditionalOnProperty(name = RefreshAutoConfiguration.REFRESH_SCOPE_ENABLED, //spring.cloud.refresh.enabled
		matchIfMissing = true)
@AutoConfigureBefore(HibernateJpaAutoConfiguration.class)
public class RefreshAutoConfiguration {
	@Bean
	@ConditionalOnMissingBean(RefreshScope.class)
	public static RefreshScope refreshScope() {
		return new RefreshScope();
	}

配置spring.cloud.refresh.enabled默认值true配置在:
/Users/baitao/.m2/repository/org/springframework/cloud/spring-cloud-commons/2.2.0.RELEASE/spring-cloud-commons-2.2.0.RELEASE.jar!/META-INF/additional-spring-configuration-metadata.json

{
	"properties": [
		{
			"defaultValue": "true",
			"name": "spring.cloud.refresh.enabled",
			"description": "Enables autoconfiguration for the refresh scope and associated features.",
			"type": "java.lang.Boolean"
		}
                ...
        ]
}

总:
1.SpringCloud程序的存在一个自动装配的类,这个类默认情况下会自动初始化一个RefreshScope实例,该实例是GenericScope的子类,然后注册到容器中。(RefreshAutoConfiguration.java, )
2.当容器启动的时候,GenericScope会自己把自己注册到scope中(ConfigurableBeanFactory#registerScope)(GenericScope)
3.然后当自定义的Bean(被@RefreshScope修饰)注册的时候,会被容器读取到其作用域为refresh。(AnnotatedBeanDefinitionReader#doRegisterBean)
通过上面三步,一个带有@RefreshScope的自定义Bean就被注册到容器中来,其作用域为refresh。
4.当我们后续进行以来查找的时候,会绕过Singleton和Prototype分支,进入最后一个分支,通过调用Scope接口的get()获取到该refresh作用域的实例。(AbstractBeanFactory.doGetBean)

深入理解Spring Cloud RefreshScope:从原理、源码到实战 RefreshScope是Spring Cloud提供的自定义Scope默认的singletonScope:Bean初始化后一直存在于容器中,配置变化无法影响已创建的Bean;refreshScope:Bean会被缓存,但支持通过「刷新操作」清空缓存——下次调用Bean时,会重新创建实例并加载最新配置。动态替换容器中的Bean实例,实现配置热更新。基础实战中使用手动触发刷新,实际生产中可能需要更灵活的方式,如「自定义刷新接口」或「基于Spring Cloud Bus的批量刷新」。 阅读详情

相关推荐

springcloud config添加@RefreshScope获取不到配置值的解决方法

1、问题 Spring Cloud Config Client 控制类添加 @RefreshScope 获取不到配置值,控制类代码如下: package com.chaoyue.configclient.controller; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.GetMapping; import org.springframew

邓邓子的博客 1751

SpringCloud配置中心

一、SpringCloud Config 微服务意味着要将单体应用中的业务拆分成一个个子服务 , 每个服务的粒度相对较小 , 因此系统中会出现大量的服务。 由于每个服务都需要必要的配置信息才能运行 , 所以一套集中式的 , 动态的配置管理设施是必不可少的。 Spring Cloud 提供了 ConfigServer 来解决这个问题 . Spring Cloud Config 为微服务架构中的微服务提供集中化的外部配置支持 , 配置服务器为各个不同微服务应用的所有环境提供了一个中心化的外部配置。 Sp

Cat_Jay_Fish的博客 1376

AFSim插件开发实战:从环境搭建到功能扩展

本文详细介绍了AFSim插件开发的完整流程,从环境搭建到功能扩展,涵盖了SDK配置、插件创建、核心代码解析、功能扩展实战、调试优化以及高级开发技巧。通过实战案例和实用技巧,帮助开发者快速掌握AFSim插件开发,提升仿真系统的扩展性和灵活性。

weixin_29309475的博客 581

九、Spring Cloud Config Server详解(八):@RefreshScope详解-手动刷新Config配置

9.9.手动刷新Config配置 当云端(我们使用gitee)我们的配置文件内容发生变化时,我们项目的客户端却没有发生变化,这怎么办呢? 1、创建一个项目:从futurecloud-config-client-eureka复制一份,得到futurecloud-config-client-eureka-refresh项目 引入依赖: <!--引入安全认证依赖--> <depe...

二总的猫 4419

l0phtcrack 7(爆破管理员密码)使用教程

l0phtcrack7简称lc7,是爆破计算机管理员密码的软件,早期是网络安全管理员用来检测系统用户是否使用了不安全的密码,后被黑客用于用户口令破解 功能:该工具支持远程破解,理论上能破解所有密码,但对复杂度比较高的密码,破解时间很长 使用前提:1.登录了需要破解的计算机 2.知道需要破解的计算机的一个管理员的账户,密码 ** 也许你会疑惑,我都知道了一个管理员账户密码了,还要另外的管理员密码...

Xiongcanne的博客 2万+

多旋翼飞行器设计与控制·Pixhawk4以及外部设备接线(笔记004)

笔记主要来源:Pixhawk 4 接线快速入门 目录 一、Pixhawk 4 的各个接口 二、接线图概览(重要传感器及外围设备) 三、飞控、GPS的安装和方向 四、电源 五、无线电遥控 六、数传电台(可选) 七、SD Card(可选) 八、电机以及其他外设 一、Pixhawk 4 的各个接口 FMU:Flight Management Unit 飞行管理组件 主 FMU 处理器:STM32F765 32 位 Arm® Cortex®-M7,216MHz,2MB...

猪猪的博客 1万+

【Spring】IoC容器 - Spring Bean作用域Scope(含SpringCloud中的RefreshScope )

前言 上一章学习了【依赖来源】,本章主要讨论SpringBean的作用域,我们这里讨论的Bean的作用域,很大程度都是默认只讨论依赖来源为【Spring BeanDefinition】的作用域,因为在我们的业务开发中,我们都是Spring框架的使用者,我们自定义的bean几乎全部都是属于【Spring BeanDefinition】的。后续文章以这个为默认前提。 作用域概览 来源 说明 singleton 默认的spring bean作用域,一个BeanFactory有且仅有一个实例

stone_tmp的博客 465

qcc304x笔记之手机端显示电量(九)

默认的sdk有些安卓手机不支持电量显示,所以需要加电量显示的补丁 流程分析 1. 首先新建一个task,并将task注册给电池模块 appBatteryRegister(batteryRegistrationForm) 实现handler处理函数,当battery模块电池电量更新后,会将电池百分比值发送到本模块,然后我们就可以在handler中将实时电量同步到手机端了。 hfpAtCmdInit atCmdTask.task.handler = appAtCmdHandleM...

在云巅的博客 2203

Spring(五)--SpringBean作用域

singleton 默认SpringBean作用域,单例,即一个BeanFactory有且仅有一个实例 prototype 每次都新建对象,Spring容器没有办法管理prototype Bean的完整生命周期,也没有办法记录示例的存在,销毁回调方法将不会执行,可以利用其他方式进行清理工作。 request作用域 sessionBean作用域 applicationBean作用域 自定义Bean作用域 实现Scope: org.springframework.beans.factory.config.Sc

Xjzzon的博客 262

Qt C++ HTTP 调用通义千问大模型 X 学术论文润色工具(SCI 格式适配)

请求地址:`https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation`;| Windows | 打包时携带 `Qt6Network.dll`/`libcrypto-1_1-x64.dll` 等依赖;| Linux | 安装 `libssl-dev` 和 `libcurl4-openssl-dev`;| API 调用失败 | 检查 API-KEY 是否有效;

寒寒豆豆软件公司的博客 104

1. linux系统下在QT中配置OPenCV开发环境

在Linux系统下配置OpenCV的开发环境,需要在官网上下载源码,并使用CMake工具对源码进行编译,与在Windows系统中配置相比复杂许多,本文linux系统为linux minit,opencv是最新版本4.7.0,不过对于linux和opencv的版本要求行不高。此项更改为自己OPenCV想要安装的路径内,默认是安装在**/usr/local。在打开的文件中添加下图中的一行代码,路径是opencv默认的安装路径。按钮,弹出下图界面,默认选择即可,然后点击。

山间点烟雨 2906

Spring Scope作用域

Spring Scope

yx_yancy1992的博客 382

【研发日记】Matlab/Simulink自动生成代码(二)——五种选择结构实现方法

相比C文本类编程语言,Simulink图形化编程语言的优势是逻辑思路和数据流清晰了很多,劣势是程序执行的时序不明确,而且各个模块的配置使编程的灵活度下降了不少,在使用习惯上面总感觉有各种限制。本文就是拆解Simulink中最基础的几个编程模块,发扬它的优势,避开劣势。

Mr.Cssust的博客 3852

SpringCloud中RefreshScope实现原理

SpringCloud中RefreshScope实现原理 jar包版本 spring-cloud-context 2.0.0.RELEASE scope基础理论 RefreshScope是springCloud在Scope的基础上实现的,因此先了解一下Scope的实现原理。 public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {

jy00733505的博客 1172

Java代码变更影响分析:从静态解析到动态调用图的实战全链路

本文介绍了Java代码提交影响分析的核心原理与实现方法。主要内容包括:1)静态分析技术,通过JavaParser解析AST构建调用图,记录类与方法间的调用关系;2)动态分析技术,使用ByteBuddy进行字节码增强,捕获运行时调用路径;3)JCCI工具实现,结合javalang、unidiff等技术分析代码改动影响,并将结果存储到SQLite数据库。文章提供了完整的代码示例,展示了从AST解析、动态调用跟踪到实际工具应用的完整技术栈,为代码变更影响分析提供了实用解决方案。

墨夶的博客 1254

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

Spring Cloud @RefreshScope 自动刷新Bean

要实现自动更新,那么需要 当Bean更新的时获取到更新后的bean,那么这个Bean需要懒加载,即使用的时候再加载 当Bean更新的时候获取最新的Bean,那么这个Bean需要重复加载,因此需要销毁原来生成的Bean,根据最新的信息创建新的Bean SpringCloud 使用@RefreshScope 来解决这个问题 以 @RefreshScope 声明的Bean将会被 org.springframework.cloud.context.scope.refresh.RefreshScope 代理...

Keep learing, and stay fast 5910

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

@RefreshScope动态刷新配置实现原理

***/该注解上除了定义注解的使用方式外,还加了一个@Scope注解,该注解定义了@Scope的名称,常用的有:singletonprototype另外就是代理的方式,因此我们可以推断,最终被标记的bean, 最终是一个代理对象。

奔跑的蜗牛的博客 3269

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

配置热更新,不想重启,如何更新Bean的状态?

通过配置中心,应用可以实时的接收到配置的变更,但是,举个例子:如果在运行时修改了 JDBC 的参数配置,此时是重启应用呢?还是修改对应 DataSource Bean 的属性呢?如果是修改 Bean 的属性,直接修改有用吗?要怎么做呢?本文将以运行时修改 JDBC 参数为例,来讨论尝试运行时修改配置,最后提出普遍的解决方案。画外音:思路比结果更重要。

qq_66627105的博客 1958

从RefreshScope实现原理看刷新配置失效问题

前言 在SpringIOC中,我们熟知的BeanScope有单例(singleton)、原型(prototype), Bean的Scope影响了Bean的创建方式,例如创建Scope=singleton的Bean时,IOC会保存实例在一个Map中,保证这个Bean在一个IOC上下文有且仅有一个实例。SpringCloud新增了一个refresh范围的scope,同样用了一种独特的方式改变了Bean的创建方式,使得其可以通过外部化配置(.properties)的刷新,在应用不需要重启的情况下热加载新的外部化配

|-| [- |_ |_ () 9692

Spring Cloud--@RefreshScope动态刷新的原理

本文介绍Spring Cloud的@RefreshScope动态刷新的原理。

IT利刃出鞘的博客 969

SpringCloud配置动态刷新@RefreshScope注解

spring cloud config或sprring cloud alibaba nacos作为配置中心,其实现原理就是通过@RefreshScope 来实现对象属性的的动态更新。 实现@RefreshScope 动态刷新的就需要以下几个: @ Scope注解 @RefreshScope注解 RefreshScope类 GenericScope类 Scope接口 ContextRefresher @RefreshScope 能实现动态刷新全仰仗着@Scope 这个注解。 一、@Scope注解 @Tar

骑个小蜗牛的博客 4万+

@RefreshScope及@Scope原理分析

截止执行LockedScopedProxyFactoryBean的setBeanFactory()里的后续代码,proxy.addAdvice(0, this),即上面添加的DelegatingIntroductionInterceptor被替换了,且将LockedScopedProxyFactoryBean自己作为拦截器。在beanFactory.getBean()的调用中,会根据bd的scope类型,利用scope的处理器获取相应的bean。接着就是反射调用target的xxmethod方法了。

ZXH240651200的博客 679

SpringCloud @RefreshScope实现原理

环境:spring cloud context2.2.8.RELEASE + spring boot 2.3.9.RELEASE。

z69183787的专栏 591

一文带你理解@RefreshScope注解实现动态刷新原理

RefeshScope这个注解想必大家都用过,在微服务配置中心的场景下经常出现,他可以用来刷新Bean中的属性配置,那大家对他的实现原理了解吗?从这边的代码中可以印证了上面的说法,创建后的Bean会缓存到scope的cache中,优先从缓存中获取,如果缓存中是null, 则重新走一遍create bean的流程。上面是RefreshScope的源码,该注解被@Scope注解使用,@Scope用来比较Spring Bean的作用域,具体使用参考相关文章。// 如果scope是单例的情况, 这里不进行分析。

乌龟的专栏 394

Spring Cloud @RefreshScope 原理分析:扫描 Bean 定义

扫描时会对注解的类的定义信息作两个操作:这个方法判断当前代理模式,如果而的这个属性是,即针对这类注解的类在扫描时,会额外创建代理类的以原始的新建一个代理类的,并且设置它的为原始对象,代理类的类型为;再注册一个以,基于原始配置的目标定义,即真正实体的定义修改了;最后再注册一个用的代理类的定义,就是偷梁换柱,完全代理了目标对象。原始类定义的为 false ,primary也为 false ,那么就能保证实力获取时优先找到的候选对象是代理对象。

Java技术攻略的博客 272
上一篇: 核爆,字节跳动算法工程师,手写1000页数据算法笔记:Github已标星79k
下一篇: Spring Boot自动装配原理和源码分析
Java佳佳
博客等级 码龄4年 216粉丝 286原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值