Value注解支持对象类型ConfigurationProperties功能

 更新时间:2022年10月24日 15:50:03   作者:uhfun  
这篇文章主要为大家介绍了Value注解支持对象类型ConfigurationProperties功能详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

真实业务场景

(不希望配置类注册为Bean 或 不希望声明@ConfigurationProperties)

假设某一个jar包内封装了DataSourceProperties

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

在jar包的Configuration中,某个@Bean的构造过程中引用了这个DataSourceProperties

public JdbcTemplate buildJdbcTemplate(DataSourceProperties dataSourceProperties) {
}

在某个业务场景中,同时存在两个DataSourceProperties 会造成一个问题,注入的时候会提示有多个候选的bean 但是没法去修改Jar包中的内容

自己重复写一个DataSourceProperties 不是很优雅

这时候引出了一个需求,DataSourceProperties不希望注册为Bean,但是能够从配置文件读取构建对象

解决方案一

使用org.springframework.boot.context.properties.bind.Binder 从配置文件构建配置对象

@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() 似乎是重复的编码方式?

解决方案二

使@Value注解能够支持自动调用这段代码 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的转换器,支持@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();
            }
        });
    }
}

转换后代码执行 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功能的详细内容,更多关于Value支持对象类型的资料请关注脚本之家其它相关文章!

相关文章

  • 图解Java经典算法冒泡排序的原理与实现

    图解Java经典算法冒泡排序的原理与实现

    冒泡排序是一种简单的排序算法,它也是一种稳定排序算法。其实现原理是重复扫描待排序序列,并比较每一对相邻的元素,当该对元素顺序不正确时进行交换。一直重复这个过程,直到没有任何两个相邻元素可以交换,就表明完成了排序
    2022-09-09
  • Spring入门到精通之注解开发详解

    Spring入门到精通之注解开发详解

    Spring是轻代码而重配置的框架,配置比较繁重,影响开发效率,所以注解开发是一种趋势。本文将通过示例为大家详细讲讲Spring如何实现注解开发,感兴趣的可以学习一下
    2022-07-07
  • SpringBoot整合MyBatis实现CRUD操作项目实践

    SpringBoot整合MyBatis实现CRUD操作项目实践

    本文主要介绍了SpringBoot整合MyBatis实现CRUD操作项目实践,如何实现数据库的CRUD创建、读取、更新、删除操作,具有一定的参考价值,感兴趣的可以了解一下
    2024-02-02
  • Java中println输出汉字乱码问题一招解决方案

    Java中println输出汉字乱码问题一招解决方案

    这篇文章主要介绍了Java中println输出汉字乱码问题一招解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-12-12
  • Java计算一个数加上100是完全平方数,加上168还是完全平方数

    Java计算一个数加上100是完全平方数,加上168还是完全平方数

    这篇文章主要介绍了Java计算一个数加上100是完全平方数,加上168还是完全平方数,需要的朋友可以参考下
    2017-02-02
  • 深入理解java中for和foreach循环

    深入理解java中for和foreach循环

    下面小编就为大家带来一篇深入理解java中for和foreach循环。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2016-07-07
  • Seata之分布式事务问题及解决方案

    Seata之分布式事务问题及解决方案

    这篇文章主要介绍了Seata之分布式事务问题及解决方案,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2025-03-03
  • IDEA修改idea64.exe.vmoptions文件以及解决coding卡顿问题

    IDEA修改idea64.exe.vmoptions文件以及解决coding卡顿问题

    IDEA修改idea64.exe.vmoptions文件以及解决coding卡顿问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-04-04
  • RabbitMQ实现消费端限流的步骤

    RabbitMQ实现消费端限流的步骤

    消费者端限流的主要目的是控制消费者每次从 RabbitMQ 中获取的消息数量,从而实现消息处理的流量控制,这篇文章主要介绍了RabbitMQ如何实现消费端限流,需要的朋友可以参考下
    2024-03-03
  • 使用JWT创建解析令牌及RSA非对称加密详解

    使用JWT创建解析令牌及RSA非对称加密详解

    这篇文章主要介绍了JWT创建解析令牌及RSA非对称加密详解,JWT是JSON Web Token的缩写,即JSON Web令牌,是一种自包含令牌,一种情况是webapi,类似之前的阿里云播放凭证的功能,另一种情况是多web服务器下实现无状态分布式身份验证,需要的朋友可以参考下
    2023-11-11

最新评论