Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the @ RefreshScope refresh mechanism?

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "what is the @ RefreshScope refresh mechanism". In the daily operation, I believe many people have doubts about what the @ RefreshScope refresh mechanism is. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "what is the @ RefreshScope refresh mechanism?" Next, please follow the editor to study!

I. Preface

Students who have used Spring Cloud know that when we use dynamic configuration refresh, we need to configure a @ RefreshScope on the class in order to dynamically update the object properties. In the attitude of knowing why, we reviewed this point again in the evening. Let's briefly talk about our understanding.

Under the overview, the following are required to implement @ RefreshScope dynamic refresh:

@ Scope

@ RefreshScope

RefreshScope

GenericScope

Scope

ContextRefresher

2. @ Scope

In a word, the dynamic refresh of @ RefreshScope depends on the annotation @ Scope. Why?

@ Scope represents the scope of Bean. Let's take a look at the properties in it:

Target ({ElementType.TYPE, ElementType.METHOD}) @ Retention (RetentionPolicy.RUNTIME) @ Documentedpublic @ interface Scope {/ * Alias for {@ link # scopeName}. * @ see # scopeName * / @ AliasFor ("scopeName") String value () default ""; / * singleton indicates that the bean is singleton. (default) * prototype indicates that the bean is multiple instances, that is, a new object is created each time the bean is used. * request in a http request, one bean corresponds to one instance. * session in a httpSession, a bean corresponds to an instance * / @ AliasFor ("value") String scopeName () default ""; / * DEFAULT does not use a proxy. (default) * NO does not use proxies, which is equivalent to DEFAULT. * INTERFACES uses an interface-based agent (jdk dynamic proxy). * TARGET_CLASS uses class-based agents (cglib). * / ScopedProxyMode proxyMode () default ScopedProxyMode.DEFAULT;}

Through the code we can clearly see the two main attributes value and proxyMode,value not to say much, we usually use to take a look at the notes. ProxyMode is interesting, and this is the essence of @ RefreshScope implementation.

What we need to care about is the ScopedProxyMode.TARGET_CLASS attribute. When ScopedProxyMode is TARGET_CLASS, a proxy object will be generated for the currently created bean, which will be accessed through the proxy object, and a new object will be created for each visit.

It may be obscure to understand, so let's take a look at the implementation and then look back at this sentence.

Third, the realization principle of RefreshScope

Let's first take a look at @ RefreshScope

@ Target ({ElementType.TYPE, ElementType.METHOD}) @ Retention (RetentionPolicy.RUNTIME) @ Scope ("refresh") @ Documentedpublic @ interface RefreshScope {/ * @ see Scope#proxyMode () * / ScopedProxyMode proxyMode () default ScopedProxyMode.TARGET_CLASS;}

two。 As you can see, it uses @ Scope, and its internal attribute defaults to ScopedProxyMode.TARGET_CLASS. Knowing that it is implemented through Spring Scope, it's easy. Let's take a look at the interface Scope.

Public interface Scope {/ * * Return the object with the given name from the underlying scope, * {@ link org.springframework.beans.factory.ObjectFactory#getObject () creating it} * if not found in the underlying storage mechanism. *

This is the central operation of a Scope, and the only operation * that is absolutely required. * @ param name the name of the object to retrieve * @ param objectFactory the {@ link ObjectFactory} to use to create the scoped * object if it is not present in the underlying storage mechanism * @ return the desired object (never {@ code null}) * @ throws IllegalStateException if the underlying scope is not currently active * / 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 ();}

Looking at the interface, we only look at Object get (String name, ObjectFactory objectFactory); this method helps us create a new bean, that is, @ RefreshScope uses this method to create a new object for us when calling refresh, so that the properties can be re-injected through spring's assembly mechanism, which implements the so-called dynamic refresh.

So how exactly does it deal with old objects, and how does it divide and create new objects?

I mentioned several important classes at the beginning, among which RefreshScope extends GenericScope, GenericScope implements Scope.

So by looking at the code, it is GenericScope that implements Scope's most important get (String name, ObjectFactory objectFactory) method, wrapping an inner class BeanLifecycleWrapperCache in GenericScope to cache the object created by adding @ RefreshScope, so that it gets the same object without refresh. (here you can think of BeanLifecycleWrapperCache as an object with a big Map caching all @ RefreshScope annotations.)

Knowing that the object is cached, all you need to do is clear the cache and recreate it when you do a dynamic refresh. When you look at the code, seeing is believing, leaving only the key methods:

/ / ContextRefresher uses it outside to make method calls = = I am the split line public synchronized Set refresh () {Set keys = refreshEnvironment (); this.scope.refreshAll (); return keys;} / / RefreshScope internal code = = I am the split line @ ManagedOperation (description = "Dispose of the current instance of all beans in this scope and force a refresh on next method execution.") Public void refreshAll () {super.destroy (); this.context.publishEvent (new RefreshScopeRefreshedEvent ()) The method in / / GenericScope = = I am the split line / / to acquire the object. If not, create and put the cache @ Override public Object get (String name, ObjectFactory objectFactory) {BeanLifecycleWrapper value = this.cache.put (name, new BeanLifecycleWrapper (name, objectFactory)); locks.putIfAbsent (name, new ReentrantReadWriteLock ()) Try {return value.getBean ();} catch (RuntimeException e) {this.errors.put (name, e); throw e }} / / for cached data cleaning @ Override public void destroy () {List errors = new ArrayList (); Collection wrappers = this.cache.clear () For (BeanLifecycleWrapper wrapper: wrappers) {try {Lock lock = locks.get (wrapper.getName ()) .writeLock (); lock.lock (); try {wrapper.destroy () } finally {lock.unlock () }} catch (RuntimeException e) {errors.add (e) }} if (! errors.isEmpty ()) {throw wrapIfNecessary (errors.get (0));} this.errors.clear ();}

By looking at the source code, we know that we have intercepted three fragments, ContextRefresher is used for the outer calling method, the get method in GenericScope is responsible for object creation and caching, and the destroy method is responsible for cleaning the cache when it is refreshed.

At this point, the study of "what is the @ RefreshScope refresh mechanism" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report