@Value在controller无法获取值 Spring注解@Value在controller无法获取到值的解决

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

@Value在controller无法获取值 Spring注解@Value在controller无法获取到值的解决

Thinkingcao   2021-11-18 我要评论
想了解Spring注解@Value在controller无法获取到值的解决的相关内容吗,Thinkingcao在本文为您仔细讲解@Value在controller无法获取值的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Spring注解,注解@Value,controller无法获取值,Spring注解@Value,下面大家一起来学习吧。

一、前言

说到@Value注解,用过的应该都知道,这是Spring3的一个注解,通过@value注解的方式获取properties文件中的属性值,大大简化了我们读取配置文件的代码

想要通过@Value注解读取配置文件属性的值,那么首先必须要配置properties文件的加载,让Spring将properties的文件中的内容加载进Spring容器中进行管理,从而可以实现通过@Value注解读取配置文件属性的值。

二、properties加入到Spring容器中有两种方式

1、以注入bean的形式

<bean id="appProperty"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <array>
            <value>classpath:weixin.properties</value>
        </array>
    </property>
</bean>

2、以下面这种形式

加载多个properties文件使用,隔开

	
    <!-- 加载配置属性文件 -->
	<context:property-placeholder ignore-unresolvable="true"        
	location="classpath:jeesite.properties,classpath:weixin.properties" />

三、将properties注册到Spring容器

1、weixin.properties内容以键值对(key = value)形式存放

2、@Value使用

以 @Value("${key}")的形式获取properties中key对应的value值 , 以下为获取value值得代码截图

5、存在问题

问题 :但是上述步骤还存在一个问题,就是我在Service中通过 @Value("${token}") 可以获取到token的值,但是在controller中无法获取到token的值,若要在Controller层也使用@Value访问properties配置的话,需要在xxx-servlet.xml(我这里是Spring-mvc.xml)中也定义properties配置文件。

解决 : 必须在Spring-mvc.xml中加入

	
    <!-- 加载配置属性文件 -->
	<context:property-placeholder ignore-unresolvable="true"        
	location="classpath:jeesite.properties,classpath:weixin.properties" />

四、总结

如上所示,同样的代码,写在在业务层,运行时能取到正确的值,但在控制层却取得了@Value注解中的Key(@Value注解有个特点,如果取不到值,那么不是返回一个null,而是返回Key)。

原因是controller注册在dispatcherservlet-servlet.xml代表的Spring MVC的容器中,而service则注册在application-context.xml代表的Spring的容器中。

如果context:property-placeholder只注册在Spring的容器中,那么自然只有业务层的类可以取到enable-upload-image的值,而控制器取不到值。 解决方法就是把各种context:property-placeholder在两个容器中都注册一下。如:

并且现在可以从属性文件读取,这只是@Value其中一小部分用法,详细请查阅资料,这次记录只是记录我在项目中所遇到的问题,方便记忆,以防止自己以后再入坑,有纰漏请指出,不喜勿喷!

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们