溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Value注解支持對象類型ConfigurationProperties功能問題怎么解決

發(fā)布時間:2022-10-26 09:19:52 來源:億速云 閱讀:113 作者:iii 欄目:開發(fā)技術(shù)

本篇內(nèi)容主要講解“Value注解支持對象類型ConfigurationProperties功能問題怎么解決”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學(xué)習(xí)“Value注解支持對象類型ConfigurationProperties功能問題怎么解決”吧!

真實業(yè)務(wù)場景

(不希望配置類注冊為Bean 或 不希望聲明@ConfigurationProperties)

假設(shè)某一個jar包內(nèi)封裝了DataSourceProperties

@Configuration
@ConfigurationProperties(
    prefix = "my.datasource"
)
@Data
public class DataSourceProperties {
    private List<String> suffix;
    private List<DataSourceDetailProperties> db;
}

在jar包的Configuration中,某個@Bean的構(gòu)造過程中引用了這個DataSourceProperties

public JdbcTemplate buildJdbcTemplate(DataSourceProperties dataSourceProperties) {
}

在某個業(yè)務(wù)場景中,同時存在兩個DataSourceProperties 會造成一個問題,注入的時候會提示有多個候選的bean 但是沒法去修改Jar包中的內(nèi)容

自己重復(fù)寫一個DataSourceProperties 不是很優(yōu)雅

這時候引出了一個需求,DataSourceProperties不希望注冊為Bean,但是能夠從配置文件讀取構(gòu)建對象

解決方案一

使用org.springframework.boot.context.properties.bind.Binder 從配置文件構(gòu)建配置對象

@Bean
public JdbcTemplate buildJdbcTemplate(Environment environment) {
     Binder binder = Binder.get(environment);
     DataSourceProperties
                properties1 = binder.bind("my.datasource1", Bindable.of(DataSourceProperties.class)).get(),
                properties2 = binder.bind("my.datasource2", Bindable.of(DataSourceProperties.class)).get();
}

binder.bind("xxx", Bindable.of(type)).get() 似乎是重復(fù)的編碼方式?

解決方案二

使@Value注解能夠支持自動調(diào)用這段代碼 binder.bind("xxx", Bindable.of(type)).get() 例如

@Bean
public JdbcTemplate buildJdbcTemplate(@Value("my.datasource1") DataSourceProperties properties1,
                                      @Value("my.datasource2") DataSourceProperties properties2) {   
}

org.springframework.beans.factory.support.DefaultListableBeanFactory#doResolveDependency 最后會交由converter處理

Class<?> type = descriptor.getDependencyType();
Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor);
if (value != null) {
    if (value instanceof String) {
        String strVal = resolveEmbeddedValue((String) value);
        BeanDefinition bd = (beanName != null && containsBean(beanName) ?
                getMergedBeanDefinition(beanName) : null);
        value = evaluateBeanDefinitionString(strVal, bd);
    }
    TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
    try {
        return converter.convertIfNecessary(value, type, descriptor.getTypeDescriptor());
    }
    catch (UnsupportedOperationException ex) {
        // A custom TypeConverter which does not support TypeDescriptor resolution...
        return (descriptor.getField() != null ?
                converter.convertIfNecessary(value, type, descriptor.getField()) :
                converter.convertIfNecessary(value, type, descriptor.getMethodParameter()));
    }
}

項目啟動時,添加String to Object的轉(zhuǎn)換器,支持@Value 并且 "bind:"開頭(防止影響@Value原有功能)

package com.nuonuo.accounting.guiding.support.spring;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.convert.ApplicationConversionService;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.ConditionalGenericConverter;
import java.util.Set;
import static java.util.Collections.singleton;
/**
 * @author uhfun
 */
public class ValuePropertiesBindableAnnotationSupport implements ApplicationContextInitializer<ConfigurableApplicationContext> {
    private static final String PREFIX = "bind:";
    @Override
    public void initialize(ConfigurableApplicationContext context) {
        Binder binder = Binder.get(context.getEnvironment());
        ((ApplicationConversionService) context.getBeanFactory().getConversionService()).addConverter(new ConditionalGenericConverter() {
            @Override
            public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
                Value value = targetType.getAnnotation(Value.class);
                return value != null && value.value().startsWith(PREFIX);
            }
            @Override
            public Set<ConvertiblePair> getConvertibleTypes() {
                return singleton(new ConvertiblePair(String.class, Object.class));
            }
            @Override
            public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
                Value value = targetType.getAnnotation(Value.class);
                Class<?> type = targetType.getType();
                assert value != null;
                return binder.bind(value.value().replace(PREFIX, ""), Bindable.of(type)).get();
            }
        });
    }
}

轉(zhuǎn)換后代碼執(zhí)行 binder.bind(value.value().replace(PREFIX, ""), Bindable.of(type)).get(); 目的就達成了

META-INF/spring.factories中添加注冊的Bean

# ApplicationContextInitializer
org.springframework.context.ApplicationContextInitializer=\
com.nuonuo.accounting.guiding.support.spring.ValuePropertiesBindableAnnotationSupport,\

最終效果

@Bean
public JdbcTemplate buildJdbcTemplate(@Value("bind:my.datasource1") DataSourceProperties properties1,
                                      @Value("bind:my.datasource2") DataSourceProperties properties2) {   
}

到此,相信大家對“Value注解支持對象類型ConfigurationProperties功能問題怎么解決”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進入相關(guān)頻道進行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI