温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

在Spring项目中使用@Value注解引入配置文件中的参数

发布时间:2020-07-11 03:45:38 来源:网络 阅读:3341 作者:pangfc 栏目:开发技术

如题所示,有时候我们的一些配置并不能在代码中“写死”,而是需要动态配置在配置文件中。这样可以使得以后需要修改该参数时只需要修改配置文件中的参数值即可,而不需要修改代码。具体配置如下:

(1)在Spring的配置文件中添加以下配置用于引入参数所在的文件:

	<bean id="configProperties"
		class="org.springframework.beans.factory.config.PropertiesFactoryBean">
		<property name="locations">
			<list>
				<value>classpath:jdbc.properties</value>
				<value>classpath:article.properties</value>
			</list>
		</property>
	</bean>
	
	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
			<property name="properties" ref="configProperties" />  
	</bean>

注:如果想在Controller中也使用@Value注解引入配置文件中的参数的话,那么需要将上面的“propertyConfigurer”这个bean在SpringMVC的配置文件中也重复复制一遍,也就是:

	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
			<property name="properties" ref="configProperties" />  
	</bean>

(2)article.properties文件的具体内容如下:

test.author=zifangsky

(3)测试:

package cn.zifangsky.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class TestController {
	
	@Value("#{configProperties['test.author']}")
	private String author;
	
	@RequestMapping("/test.html")
	public void test(){
		System.out.println("---------------");
		System.out.println("测试: " + author);
	}
}

可以看出,这里使用了@Value注解,其语法如下:

@Value(“#{configProperties[‘参数名’]}”)

当然,还有一种简写的语法是:

@Value(“${参数名}”)

也就是说上面加载参数那里也可以这样使用:

	@Value("${test.author}")
	private String author;

(4)最后输出如下:

---------------
测试: zifangsky


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI