SpringBoot2動態@Value怎麼實現
具體的實作步驟分為以下幾步
1.透過BeanPostProcessor取得有使用@Value註解的bean,並儲存到map中
2.動態修改map中的bean欄位的值
取得bean
先寫一個類別實作BeanPostProcessor接口,只需要使用其中的一個函數就可以。前後都可以用來實現,並不影響最終的使用,因為咱們只是需要bean的實例。
接下來看一下具體實作程式碼
package com.allen.apollo; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.context.annotation.Configuration; import org.springframework.util.ReflectionUtils; import java.lang.reflect.Field; import java.util.LinkedList; import java.util.List; import java.util.Set; @Configuration public class SpringValueProcessor implements BeanPostProcessor { private final PlaceholderHelper placeholderHelper = new PlaceholderHelper(); @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (beanName.equals("springValueController")) { Class obj = bean.getClass(); List<Field> fields = findAllField(obj); for (Field field : fields) { Value value = field.getAnnotation(Value.class); if (value != null) { Set<String> keys = placeholderHelper.extractPlaceholderKeys(value.value()); for (String key : keys) { SpringValue springValue = new SpringValue(key, value.value(), bean, beanName, field, false); SpringValueCacheMap.map.put(key, springValue); } } } } return bean; } private List<Field> findAllField(Class clazz) { final List<Field> res = new LinkedList<>(); ReflectionUtils.doWithFields(clazz, new ReflectionUtils.FieldCallback() { @Override public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { res.add(field); } }); return res; } }
上面的程式碼咱們就已經拿到了SpringValueController這個實例bean並儲存到了map當中,下面看一下測試程式碼
/** * cache field,存储bean 字段 */ package com.allen.apollo; import com.google.common.collect.LinkedListMultimap; import com.google.common.collect.Multimap; public class SpringValueCacheMap { public static final Multimap<String, SpringValue> map = LinkedListMultimap.create(); }
package com.allen.apollo; import java.lang.ref.WeakReference; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Type; import org.springframework.core.MethodParameter; public class SpringValue { private MethodParameter methodParameter; private Field field; private WeakReference<Object> beanRef; private String beanName; private String key; private String placeholder; private Class<?> targetType; private Type genericType; private boolean isJson; public SpringValue(String key, String placeholder, Object bean, String beanName, Field field, boolean isJson) { this.beanRef = new WeakReference<>(bean); this.beanName = beanName; this.field = field; this.key = key; this.placeholder = placeholder; this.targetType = field.getType(); this.isJson = isJson; if (isJson) { this.genericType = field.getGenericType(); } } public SpringValue(String key, String placeholder, Object bean, String beanName, Method method, boolean isJson) { this.beanRef = new WeakReference<>(bean); this.beanName = beanName; this.methodParameter = new MethodParameter(method, 0); this.key = key; this.placeholder = placeholder; Class<?>[] paramTps = method.getParameterTypes(); this.targetType = paramTps[0]; this.isJson = isJson; if (isJson) { this.genericType = method.getGenericParameterTypes()[0]; } } public void update(Object newVal) throws IllegalAccessException, InvocationTargetException { if (isField()) { injectField(newVal); } else { injectMethod(newVal); } } private void injectField(Object newVal) throws IllegalAccessException { Object bean = beanRef.get(); if (bean == null) { return; } boolean accessible = field.isAccessible(); field.setAccessible(true); field.set(bean, newVal); field.setAccessible(accessible); } private void injectMethod(Object newVal) throws InvocationTargetException, IllegalAccessException { Object bean = beanRef.get(); if (bean == null) { return; } methodParameter.getMethod().invoke(bean, newVal); } public String getBeanName() { return beanName; } public Class<?> getTargetType() { return targetType; } public String getPlaceholder() { return this.placeholder; } public MethodParameter getMethodParameter() { return methodParameter; } public boolean isField() { return this.field != null; } public Field getField() { return field; } public Type getGenericType() { return genericType; } public boolean isJson() { return isJson; } boolean isTargetBeanValid() { return beanRef.get() != null; } @Override public String toString() { Object bean = beanRef.get(); if (bean == null) { return ""; } if (isField()) { return String .format("key: %s, beanName: %s, field: %s.%s", key, beanName, bean.getClass().getName(), field.getName()); } return String.format("key: %s, beanName: %s, method: %s.%s", key, beanName, bean.getClass().getName(), methodParameter.getMethod().getName()); } }
package com.allen.apollo; import com.google.common.base.Strings; import com.google.common.collect.Sets; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanExpressionContext; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.beans.factory.config.Scope; import org.springframework.util.StringUtils; import java.util.Set; import java.util.Stack; /** * Placeholder helper functions. */ public class PlaceholderHelper { private static final String PLACEHOLDER_PREFIX = "${"; private static final String PLACEHOLDER_SUFFIX = "}"; private static final String VALUE_SEPARATOR = ":"; private static final String SIMPLE_PLACEHOLDER_PREFIX = "{"; private static final String EXPRESSION_PREFIX = "#{"; private static final String EXPRESSION_SUFFIX = "}"; /** * Resolve placeholder property values, e.g. * <br /> * <br /> * "${somePropertyValue}" -> "the actual property value" */ public Object resolvePropertyValue(ConfigurableBeanFactory beanFactory, String beanName, String placeholder) { // resolve string value String strVal = beanFactory.resolveEmbeddedValue(placeholder); BeanDefinition bd = (beanFactory.containsBean(beanName) ? beanFactory .getMergedBeanDefinition(beanName) : null); // resolve expressions like "#{systemProperties.myProp}" return evaluateBeanDefinitionString(beanFactory, strVal, bd); } private Object evaluateBeanDefinitionString(ConfigurableBeanFactory beanFactory, String value, BeanDefinition beanDefinition) { if (beanFactory.getBeanExpressionResolver() == null) { return value; } Scope scope = (beanDefinition != null ? beanFactory .getRegisteredScope(beanDefinition.getScope()) : null); return beanFactory.getBeanExpressionResolver() .evaluate(value, new BeanExpressionContext(beanFactory, scope)); } /** * Extract keys from placeholder, e.g. * <ul> * <li>${some.key} => "some.key"</li> * <li>${some.key:${some.other.key:100}} => "some.key", "some.other.key"</li> * <li>${${some.key}} => "some.key"</li> * <li>${${some.key:other.key}} => "some.key"</li> * <li>${${some.key}:${another.key}} => "some.key", "another.key"</li> * <li>#{new java.text.SimpleDateFormat("${some.key}").parse("${another.key}")} => "some.key", "another.key"</li> * </ul> */ public Set<String> extractPlaceholderKeys(String propertyString) { Set<String> placeholderKeys = Sets.newHashSet(); if (!isNormalizedPlaceholder(propertyString) && !isExpressionWithPlaceholder(propertyString)) { return placeholderKeys; } Stack<String> stack = new Stack<>(); stack.push(propertyString); while (!stack.isEmpty()) { String strVal = stack.pop(); int startIndex = strVal.indexOf(PLACEHOLDER_PREFIX); if (startIndex == -1) { placeholderKeys.add(strVal); continue; } int endIndex = findPlaceholderEndIndex(strVal, startIndex); if (endIndex == -1) { // invalid placeholder? continue; } String placeholderCandidate = strVal.substring(startIndex + PLACEHOLDER_PREFIX.length(), endIndex); // ${some.key:other.key} if (placeholderCandidate.startsWith(PLACEHOLDER_PREFIX)) { stack.push(placeholderCandidate); } else { // some.key:${some.other.key:100} int separatorIndex = placeholderCandidate.indexOf(VALUE_SEPARATOR); if (separatorIndex == -1) { stack.push(placeholderCandidate); } else { stack.push(placeholderCandidate.substring(0, separatorIndex)); String defaultValuePart = normalizeToPlaceholder(placeholderCandidate.substring(separatorIndex + VALUE_SEPARATOR.length())); if (!Strings.isNullOrEmpty(defaultValuePart)) { stack.push(defaultValuePart); } } } // has remaining part, e.g. ${a}.${b} if (endIndex + PLACEHOLDER_SUFFIX.length() < strVal.length() - 1) { String remainingPart = normalizeToPlaceholder(strVal.substring(endIndex + PLACEHOLDER_SUFFIX.length())); if (!Strings.isNullOrEmpty(remainingPart)) { stack.push(remainingPart); } } } return placeholderKeys; } private boolean isNormalizedPlaceholder(String propertyString) { return propertyString.startsWith(PLACEHOLDER_PREFIX) && propertyString.endsWith(PLACEHOLDER_SUFFIX); } private boolean isExpressionWithPlaceholder(String propertyString) { return propertyString.startsWith(EXPRESSION_PREFIX) && propertyString.endsWith(EXPRESSION_SUFFIX) && propertyString.contains(PLACEHOLDER_PREFIX); } private String normalizeToPlaceholder(String strVal) { int startIndex = strVal.indexOf(PLACEHOLDER_PREFIX); if (startIndex == -1) { return null; } int endIndex = strVal.lastIndexOf(PLACEHOLDER_SUFFIX); if (endIndex == -1) { return null; } return strVal.substring(startIndex, endIndex + PLACEHOLDER_SUFFIX.length()); } private int findPlaceholderEndIndex(CharSequence buf, int startIndex) { int index = startIndex + PLACEHOLDER_PREFIX.length(); int withinNestedPlaceholder = 0; while (index < buf.length()) { if (StringUtils.substringMatch(buf, index, PLACEHOLDER_SUFFIX)) { if (withinNestedPlaceholder > 0) { withinNestedPlaceholder--; index = index + PLACEHOLDER_SUFFIX.length(); } else { return index; } } else if (StringUtils.substringMatch(buf, index, SIMPLE_PLACEHOLDER_PREFIX)) { withinNestedPlaceholder++; index = index + SIMPLE_PLACEHOLDER_PREFIX.length(); } else { index++; } } return -1; } }
package com.allen.apollo; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.lang.reflect.InvocationTargetException; @RestController @Slf4j public class SpringValueController { @Value("${test:123}") public String zax; @Value("${test:123}") public String test; @Value(("${zed:zed}")) public String zed; @GetMapping("/test") public String test(String a, String b) { if (!StringUtils.isEmpty(a)) { try { for (SpringValue springValue : SpringValueCacheMap.map.get("test")) { springValue.update(a); } for (SpringValue springValue : SpringValueCacheMap.map.get("zed")) { springValue.update(b); } } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } return String.format("test: %s, zax: %s, zed: %s", test, zax, zed); } }
以上是SpringBoot2動態@Value怎麼實現的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

熱門話題

Jasypt介紹Jasypt是一個java庫,它允許開發員以最少的努力為他/她的專案添加基本的加密功能,並且不需要對加密工作原理有深入的了解用於單向和雙向加密的高安全性、基於標準的加密技術。加密密碼,文本,數字,二進位檔案...適合整合到基於Spring的應用程式中,開放API,用於任何JCE提供者...添加如下依賴:com.github.ulisesbocchiojasypt-spring-boot-starter2. 1.1Jasypt好處保護我們的系統安全,即使程式碼洩露,也可以保證資料來源的

使用場景1、下單成功,30分鐘未支付。支付超時,自動取消訂單2、訂單簽收,簽收後7天未進行評估。訂單超時未評價,系統預設好評3、下單成功,商家5分鐘未接單,訂單取消4、配送超時,推播簡訊提醒…對於延時比較長的場景、即時性不高的場景,我們可以採用任務調度的方式定時輪詢處理。如:xxl-job今天我們採

一、Redis實現分散式鎖原理為什麼需要分散式鎖在聊分散式鎖之前,有必要先解釋一下,為什麼需要分散式鎖。與分散式鎖相對就的是單機鎖,我們在寫多執行緒程式時,避免同時操作一個共享變數產生資料問題,通常會使用一把鎖來互斥以保證共享變數的正確性,其使用範圍是在同一個進程中。如果換做是多個進程,需要同時操作一個共享資源,如何互斥?現在的業務應用通常是微服務架構,這也意味著一個應用會部署多個進程,多個進程如果需要修改MySQL中的同一行記錄,為了避免操作亂序導致髒數據,此時就需要引入分佈式鎖了。想要實現分

springboot讀取文件,打成jar包後訪問不到最新開發出現一種情況,springboot打成jar包後讀取不到文件,原因是打包之後,文件的虛擬路徑是無效的,只能通過流去讀取。文件在resources下publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

SpringBoot和SpringMVC都是Java開發中常用的框架,但它們之間有一些明顯的差異。本文將探究這兩個框架的特點和用途,並對它們的差異進行比較。首先,我們來了解一下SpringBoot。 SpringBoot是由Pivotal團隊開發的,它旨在簡化基於Spring框架的應用程式的建立和部署。它提供了一種快速、輕量級的方式來建立獨立的、可執行

在Springboot+Mybatis-plus不使用SQL語句進行多表添加操作我所遇到的問題準備工作在測試環境下模擬思維分解一下:創建出一個帶有參數的BrandDTO對像模擬對後台傳遞參數我所遇到的問題我們都知道,在我們使用Mybatis-plus中進行多表操作是極其困難的,如果你不使用Mybatis-plus-join這一類的工具,你只能去配置對應的Mapper.xml文件,配置又臭又長的ResultMap,然後再寫對應的sql語句,這種方法雖然看上去很麻煩,但具有很高的靈活性,可以讓我們

1.自訂RedisTemplate1.1、RedisAPI預設序列化機制基於API的Redis快取實作是使用RedisTemplate範本進行資料快取操作的,這裡開啟RedisTemplate類,查看該類別的源碼資訊publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations,BeanClassLoaderAware{//聲明了value的各種序列化方式,初始值為空@NullableprivateRedisSe

在專案中,很多時候需要用到一些配置信息,這些信息在測試環境和生產環境下可能會有不同的配置,後面根據實際業務情況有可能還需要再做修改。我們不能將這些設定在程式碼中寫死,最好是寫到設定檔中,例如可以把這些資訊寫到application.yml檔案中。那麼,怎麼在程式碼裡取得或使用這個位址呢?有2個方法。方法一:我們可以透過@Value註解的${key}即可取得設定檔(application.yml)中和key對應的value值,這個方法適用於微服務比較少的情形方法二:在實際專案中,遇到業務繁瑣,邏
