• 180612-Spring之Yml配置文件加载问题


    logo

    Yml配置文件加载问题

    在resource目录下有一个application.yml文件,希望是通过@PropertySource注解,将配置文件数据读取到Environment中,然而调试发现数据始终读取不到,google之后,记录下解决方法

    在测试用例中,指定初始化方式 @ContextConfiguration(classes = RedisConf.class, initializers = ConfigFileApplicationContextInitializer.class)

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(classes = RedisConf.class, initializers = ConfigFileApplicationContextInitializer.class)
    public class RedisTest {
        @Test
        public void testRedis() {
            String ans = JedisClient.getStr("hello");
            System.out.println(ans);
        }
    }
    

    对应的配置类

    @Configuration
    @PropertySource(value = "classpath:application.yml")
    public class RedisConf {
    
        @Autowired
        private Environment environment;
    
        @Autowired
        public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
            RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
            redisTemplate.setConnectionFactory(redisConnectionFactory);
    
            DefaultStrSerializer serializer = new DefaultStrSerializer();
            redisTemplate.setValueSerializer(serializer);
            redisTemplate.setHashValueSerializer(serializer);
            redisTemplate.setKeySerializer(serializer);
            redisTemplate.setHashKeySerializer(serializer);
    
            redisTemplate.afterPropertiesSet();
    
            JedisClient.register(redisTemplate);
            return redisTemplate;
        }
    
        @Bean
        public RedisConnectionFactory redisConnectionFactory() {
            LettuceConnectionFactory fac = new LettuceConnectionFactory();
            fac.getStandaloneConfiguration().setHostName(environment.getProperty("spring.redis.host"));
            fac.getStandaloneConfiguration().setPort(Integer.parseInt(environment.getProperty("spring.redis.port")));
            fac.getStandaloneConfiguration()
                    .setPassword(RedisPassword.of(environment.getProperty("spring.redis.password")));
            fac.afterPropertiesSet();
            return fac;
        }
    }
    

    II. 其他

    1. 一灰灰Bloghttps://liuyueyi.github.io/hexblog

    一灰灰的个人博客,记录所有学习和工作中的博文,欢迎大家前去逛逛

    2. 声明

    尽信书则不如,已上内容,纯属一家之言,因个人能力有限,难免有疏漏和错误之处,如发现bug或者有更好的建议,欢迎批评指正,不吝感激

    3. 扫描关注

    blogInfoV2.png

  • 相关阅读:
    内存中字的存储
    代码段
    CPU运行的流程
    字的传送
    内存中字的存储
    c语言中求数组元素的最大值和最小值
    linux系统 centos8.3 中安装 Rsudio
    Error in .External2(C_X11, paste0("png::", filename), g$width, g$height, : 解决linux R绘图问题
    linux系统中使用R的Cairo绘制png格式图片
    c语言中利用二维数组统计考试成绩之和
  • 原文地址:https://www.cnblogs.com/yihuihui/p/9174722.html
Copyright © 2020-2023  润新知