使用@Value读取yml配置文件编译报错

直接上编译时发生的错误

Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'spring.redis.cache.on' in value "${spring.redis.cache.on}"

yml文件部分配置:

spring:
    #--------------------------------------------------
    #  DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
    #--------------------------------------------------   
    cache:
        type: redis
    redis:
        host: localhost
        port: 6379
        password: null
        pool:
            # 最大连接数
            max-active: 100
            # 最大空闲数,空闲链接数大于maxIdle时,将进行回收
            max-idle: 8
            # 最小空闲数,低于minIdle时,将创建新的链接
            min-idle: 0
            # 最大等待数
            max-wait: 100000
        timeout: 0
        database: 0
        # 自定义的要获取的配置
        cache:
            on: true

@Value获取配置文件配置部分代码

@Aspect
@Component
public class RedisCacheAspect {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 是否开启redis缓存,将查询的结果写入value
     */
    @Value(value = "${spring.redis.cache.on}")
    private Boolean isOn =true;

   //此处省略其它代码
}

按照官方给出的方式进行@Value方式获取,应该是没有问题的,那么问题出在哪里呢?

测试一:我们将上面的配置文件.yml换成.properties,@Value获取配置的方式不变,如下:

 #--------------------------------------------------
 #  DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
 #--------------------------------------------------   
spring.cache.type=redis
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=null
spring.redis.pool.max-active=100
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.pool.max-wait=100000
spring.redis.database=0
# 自定义的要获取的配置
spring.redis.cache.on=true 

经过测试,发现程序可以正常编译通过,并通过Debug测试发现值可以正常获取。

测试二:我们将上面的配置文件.yml中所配置的on属性修改为ison,@Value获取配置的方式相应修改为@Value(value = "${spring.redis.cache.ison}")。如下:

 #--------------------------------------------------
 #  DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
 #--------------------------------------------------   
spring.cache.type=redis
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=null
spring.redis.pool.max-active=100
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.pool.max-wait=100000
spring.redis.database=0
# 自定义的要获取的配置
spring.redis.cache.ison=true 

经测试后,发现程序可以正常编译通过,并通过Debug测试发现值可以正常获取。

结论:在我们使用yml进行自定义配置项时,要注意配置项的名称,我们推测可能使用on作为配置项名称涉及到了yml配置文件的关键字,导致无法正常解析配置项,如有知道原因的欢迎下方留言,一起讨论。

另外,使用.properties文件和.yml文件作为配置文件使用@Value获取配置项时,还存在一点区别:

在IDEA中测试发现,当使用.properties文件时,按下Ctrl鼠标放在${spring.redis.cache.ison}上是可以定位到配置文件的位置的。但是使用.yml文件,做相同操作时无法定位到相应的配置文件位置。不过二者都是可以正常使用的,只是IDEA支持上面的区别而已。

您可以使用yaml库来读取yml文件并使用@Value注释将其注入到Spring Boot应用程序中。首先,您需要在pom.xml文件中添加yaml依赖项: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> <version>2.5.4</version> </dependency> ``` 然后,在您的Spring Boot应用程序中,您可以使用以下代码来读取yml文件并将其注入到应用程序中: ```java import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; @Configuration @PropertySource(value = "classpath:application.yml", factory = YamlPropertySourceFactory.class) public class YamlConfig { @Value("${property.key}") private String propertyValue; public String getPropertyValue() { return propertyValue; } } ``` 在上面的代码中,我们使用@PropertySource注释将yml文件路径指定为"classpath:application.yml",并使用YamlPropertySourceFactory类来加载yml文件。然后,我们使用@Value注释将yml属性注入到应用程序中。 请注意,YamlPropertySourceFactory类是一个自定义工厂类,用于将yml文件转换为属性源。以下是该类的代码: ```java import org.springframework.beans.factory.config.YamlPropertiesFactoryBean; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PropertiesLoaderUtils; import org.springframework.core.io.support.PropertySourceFactory; import org.springframework.core.env.PropertiesPropertySource; import org.springframework.core.env.PropertySource; import java.io.IOException; import java.util.Properties; public class YamlPropertySourceFactory implements PropertySourceFactory { @Override public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException { Resource yamlResource = new ClassPathResource("application.yml"); Properties propertiesFromYaml = loadYamlIntoProperties(yamlResource); String sourceName = name != null ? name : resource.getResource().getFilename(); return new PropertiesPropertySource(sourceName, propertiesFromYaml); } private Properties loadYamlIntoProperties(Resource yaml) throws IOException { YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean(); factory.setResources(yaml); Properties properties = factory.getObject(); return properties != null ? properties : new Properties(); } } ``` 这样,您就可以使用@Value注释将yml文件中的属性注入到Spring Boot应用程序中了。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值