springboot手写自定义配置

Posted Fire king

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot手写自定义配置相关的知识,希望对你有一定的参考价值。

阅读之前建议先看springboot自定义配置应用详解

  1. demo
@ConfigurationProperties(
        prefix = "xulehuang.redis" //yml或者properties文件里面属性的前缀,前缀加具体属性名就对应RabbitProperties 的属性名,值自然而然也会取到
)
@Configuration
@Data
public class MyRedisProperties 
    private String hostName;
    private String port;
    private String password;
    private String database;



@Configuration
@EnableConfigurationProperties(MyRedisProperties.class)
public class MyRedisConfig 

    @Bean
    public RedisTemplate<Object, Object> redisTemplate(MyRedisProperties myRedisProperties ,RedisConnectionFactory redisConnectionFactory) 
        RedisTemplate<Object, Object> template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        template.setKeySerializer(jackson2JsonRedisSerializer());
        template.setValueSerializer(jackson2JsonRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jackson2JsonRedisSerializer());
        template.afterPropertiesSet();
        logger().info("加载Redis模板方法:", template.getClass());
        return template;
    

    @Bean
    public RedisSerializer<Object> jackson2JsonRedisSerializer()         //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(mapper);
        logger().info("加载Redis序列化方法:", serializer.getClass());
        return serializer;
    

    @Bean
    public Logger logger() 
        return  LoggerFactory.getLogger(MyRedisConfig.class);
    

    @Bean
    public RedisStandaloneConfiguration redisStandaloneConfiguration( MyRedisProperties myRedisProperties) 
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(myRedisProperties.getHostName(), Integer.valueOf(myRedisProperties.getPort()));
        redisStandaloneConfiguration.setPassword(myRedisProperties.getPassword());
        redisStandaloneConfiguration.setDatabase(Integer.valueOf(myRedisProperties.getDatabase()));
        return redisStandaloneConfiguration;
    


```yml
xulehuang.redis.hostName = ip
xulehuang.redis.port =  自定义
xulehuang.redis.database =  自定义
xulehuang.redis.password =  自己的密码
  1. 难点剖析

关键在于如何找到有host、name和password的类,然后去注册为bean就可以了。我是从public RedisTemplate<Object, Object> redisTemplate(MyRedisProperties myRedisProperties ,RedisConnectionFactory redisConnectionFactory)中的setConnectionFactory debug出来的,发现configuration属性是RedisStandaloneConfiguration类的,而且有默认实现,所以就new了一个,然后配合我的MyRedisProperties 类去自定义它。同时,默认是LettuceConnectionFactory实现RedisConnectionFactory 。

  1. debug三个构造方法,确定调用关系
    不难发现configuration = standaloneConfig ,而standaloneConfig 正是有我们想要的属性,同时默认实现符合预期,所以我们就自定义一个再去注册它。
private LettuceConnectionFactory(LettuceClientConfiguration clientConfig) 
        this.log = LogFactory.getLog(this.getClass());
        this.validateConnection = false;
        this.shareNativeConnection = true;
        this.eagerInitialization = false;
        this.connectionMonitor = new Object();
        this.convertPipelineAndTxResults = true;
        this.standaloneConfig = new RedisStandaloneConfiguration("localhost", 6379);
        this.pipeliningFlushPolicy = PipeliningFlushPolicy.flushEachCommand();
        Assert.notNull(clientConfig, "LettuceClientConfiguration must not be null!");
        this.clientConfiguration = clientConfig;
        this.configuration = this.standaloneConfig;
    
  1. 为什么debug的时候 this.standaloneConfig有值?

这就是spring ioc的问题了,configuration 是这个类的属性,实例化的时候就会去找对应的实现实例化

  1. 使用@ConfigurationProperties要加入
<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
			<optional>true</optional>
		</dependency>
  1. 在原有的redis依赖上做的修改,要加入
<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>

以上是关于springboot手写自定义配置的主要内容,如果未能解决你的问题,请参考以下文章

手写自定义springboot-starter,感受框架的魅力和原理

从零开始学springboot-6.手写拦截器和自定义注解

手写一个SpringBoot-Starter

阿里微服务专家手写Spring Boot 实现一个简单的自动配置模块

自定义springboot-starter,感受框架的魅力和原理

关于手写实现Spring注解实现自定义配置功能