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 function of TargetSource in Springboot

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article will explain in detail what the role of TargetSource in Springboot is, the content of the article is of high quality, so the editor will share it with you for reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.

Summary:

In fact, proxy agent is not target, but TargetSource, this is very important, we must distinguish!

In general, a proxy object can only proxy one target, and the target of each method call is the only fixed target. However, if you let proxy proxy TargetSource, you can make the target instance of each method call different (or the same, depending on the TargetSource implementation). This mechanism makes method invocation flexible and can extend many advanced functions, such as simple interest, prototype, local thread, target object pool, runtime target object hot replacement target source, and so on.

Spring built-in TargetSourceSingletonTargetSource public class SingletonTargetSource implements TargetSource, Serializable {/ * * Target cached and invoked using reflection. * / private final Object target; / / omit extraneous code. @ Override public Object getTarget () {return this.target;} / / omit extraneous code. }

The target object obtained from this target source is singleton, and the member variable target caches the target object, which is returned each time getTarget ().

PrototypeTargetSource public class PrototypeTargetSource extends AbstractPrototypeBasedTargetSource {/ * * Obtain a new prototype instance for every call. * @ see # newPrototypeInstance () * / @ Override public Object getTarget () throws BeansException {return newPrototypeInstance ();} / * * Destroy the given independent instance. * @ see # destroyPrototypeInstance * / @ Override public void releaseTarget (Object target) {destroyPrototypeInstance (target);} / omit extraneous code. }

Each time getTarget () generates a bean of type prototype, that is, its generated bean is not singleton, so when using this type of TargetSource, it is important to note that the encapsulated target bean must be of type prototype. PrototypeTargetSource inherits AbstractBeanFactoryBasedTargetSource's ability to create bean.

Public abstract class AbstractPrototypeBasedTargetSource extends AbstractBeanFactoryBasedTargetSource {/ / omit extraneous code. / * Subclasses should call this method to create a new prototype instance. * @ throws BeansException if bean creation failed * / protected Object newPrototypeInstance () throws BeansException {if (logger.isDebugEnabled ()) {logger.debug ("Creating new instance of bean'" + getTargetBeanName () + "'");} return getBeanFactory () .getBean (getTargetBeanName ());} / * * Subclasses should call this method to destroy an obsolete prototype instance. * @ param target the bean instance to destroy * / protected void destroyPrototypeInstance (Object target) {if (logger.isDebugEnabled ()) {logger.debug ("Destroying instanceof bean'" + getTargetBeanName () + "'");} if (getBeanFactory () instanceof ConfigurableBeanFactory) {((ConfigurableBeanFactory) getBeanFactory ()) .destroyBean (getTargetBeanName (), target) } else if (target instanceof DisposableBean) {try {((DisposableBean) target) .destroy ();} catch (Throwable ex) {logger.warn ("Destroy method on bean with name'" + getTargetBeanName () + "'threw an exception", ex) } / / omit extraneous code. }

As you can see, PrototypeTargetSource's way of generating prototype type bean is mainly delegated to BeanFactory, because BeanFactory has its own set of logic to generate prototype type bean, so PrototypeTargetSource also has the ability to generate prototype type bean, which is why the target bean we want to generate must be declared as prototype type.

ThreadLocalTargetSource public class ThreadLocalTargetSource extends AbstractPrototypeBasedTargetSource implements ThreadLocalTargetSourceStats, DisposableBean {/ * ThreadLocal holding the target associated with the current * thread. Unlike most ThreadLocals, which are static, this variable * is meant to be per thread per instance of the ThreadLocalTargetSource class. * / private final ThreadLocal targetInThread = new NamedThreadLocal ("Thread-local instance of bean'" + getTargetBeanName () + "'"); / * * Set of managed targets, enabling us to keep track of the targets we've created. * / private final Set targetSet = new HashSet (); / / omit extraneous code. / * Implementation of abstract getTarget () method. * We look for a target held in a ThreadLocal. If we don't find one, * we create one and bind it to the thread. No synchronization is required. * / @ Override public Object getTarget () throws BeansException {+ + this.invocationCount; Object target = this.targetInThread.get () If (target = = null) {if (logger.isDebugEnabled ()) {logger.debug ("No target for prototype'" + getTargetBeanName () + "bound to thread:" + "creating one and binding it to thread"+ Thread.currentThread (). GetName () +");} / / Associate target with ThreadLocal. Target = newPrototypeInstance (); this.targetInThread.set (target); synchronized (this.targetSet) {this.targetSet.add (target);} else {+ + this.hitCount;} return target;} / * Dispose of targets if necessary; clear ThreadLocal. * @ see # destroyPrototypeInstance * / @ Override public void destroy () {logger.debug ("Destroying ThreadLocalTargetSource bindings"); synchronized (this.targetSet) {for (Object target: this.targetSet) {destroyPrototypeInstance (target);} this.targetSet.clear ();} / Clear ThreadLocal, just in case. This.targetInThread.remove ();} / / omit extraneous code. }

ThreadLocalTargetSource is the TargetSource bound to the thread, and it is understandable that its underlying implementation must use ThreadLocal. Now that ThreadLocal is used, we need to pay attention to two issues:

The target object must be declared to be of type prototype because each thread holds a different object

The target object must be stateless because the target object is bound to the current thread, and Spring uses a thread pool to handle requests, so each thread may handle different requests, so to avoid problems, the target object must be stateless.

Implement custom TargetSource package com.github.dqqzj.springboot.target; import org.springframework.aop.TargetSource; import org.springframework.util.Assert; import java.lang.reflect.Array; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicInteger / * @ author qinzhongjian * @ date created in 2019-08-25 12:43 * @ description: TODO * @ since JDK 1.8.0_212-b10z * / public class DqqzjTargetSource implements TargetSource {private final AtomicInteger idx = new AtomicInteger (); private final Object [] target;; public DqqzjTargetSource (Object [] target) {Assert.notNull (target, "Target object must not be null") This.target = target;} @ Override public Class getTargetClass () {return target.getClass ();} @ Override public boolean isStatic () {return false;} @ Override public Object getTarget () throws Exception {return this.target [this.idx.getAndIncrement () & this.target.length-1] } @ Override public void releaseTarget (Object target) throws Exception {}}

There are two main points to pay attention to in implementing a custom TargetSource, one is the getTarget () method, which needs to implement the logic of getting the target object, and the other is the isStatic () method, which tells Spring whether the target object needs to be cached or not, and generally returns false in non-singleton cases.

About what the role of TargetSource in Springboot is shared here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

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