首页 文章资讯内容详情

spring之@Value详解(转载)

2026-06-01 2 花语

本文内容纲要:

-@Value注入 -不通过配置文件的注入属性的情况 -通过配置文件的注入属性的情况

@Value注入

不通过配置文件的注入属性的情况

通过@Value将外部的值动态注入到Bean中,使用的情况有:

注入普通字符串

注入操作系统属性

注入表达式结果

注入其他Bean属性:注入beanInject对象的属性another

注入文件资源

注入URL资源

详细代码见:

@Value("normal") privateStringnormal;//注入普通字符串

@Value("#{systemProperties[os.name]}") privateStringsystemPropertiesName;//注入操作系统属性 @Value("#{T(java.lang.Math).random()*100.0}") privatedoublerandomNumber;//注入表达式结果 @Value("#{beanInject.another}") privateStringfromAnotherBean;//注入其他Bean属性:注入beanInject对象的属性another,类具体定义见下面 @Value("classpath:com/hry/spring/configinject/config.txt") privateResourceresourceFile;//注入文件资源 @Value("http://www.baidu.com") privateResourcetestUrl;//注入URL资源

注入其他Bean属性:注入beanInject对象的属性another

@Component publicclassBeanInject{ @Value("其他Bean的属性") privateStringanother; publicStringgetAnother(){ returnanother; } publicvoidsetAnother(Stringanother){ this.another=another; } }

通过配置文件的注入属性的情况

通过@Value将外部配置文件的值动态注入到Bean中。配置文件主要有两类:

application.properties。application.properties在springboot启动时默认加载此文件 自定义属性文件。自定义属性文件通过@PropertySource加载。@PropertySource可以同时加载多个文件,也可以加载单个文件。如果相同第一个属性文件和第二属性文件存在相同key,则最后一个属性文件里的key启作用。加载文件的路径也可以配置变量,如下文的${anotherfile.configinject},此值定义在第一个属性文件config.properties

第一个属性文件config.properties内容如下:

${anotherfile.configinject}作为第二个属性文件加载路径的变量值 book.name=bookName anotherfile.configinject=placeholder

第二个属性文件config_placeholder.properties内容如下:

book.name.placeholder=bookNamePlaceholder

下面通过@Value(“${app.name}”)语法将属性文件的值注入bean属性值,详细代码见:

@Component //引入外部配置文件组:${app.configinject}的值来自config.properties。 //如果相同 @PropertySource({"classpath:com/hry/spring/configinject/config.properties", "classpath:com/hry/spring/configinject/config_${anotherfile.configinject}.properties"}) publicclassConfigurationFileInject{ @Value("${app.name}") privateStringappName;//这里的值来自application.properties,springboot启动时默认加载此文件 @Value("${book.name}") privateStringbookName;//注入第一个配置外部文件属性 @Value("${book.name.placeholder}") privateStringbookNamePlaceholder;//注入第二个配置外部文件属性 @Autowired privateEnvironmentenv;//注入环境变量对象,存储注入的属性值 publicStringtoString(){ StringBuildersb=newStringBuilder(); sb.append("bookName=").append(bookName).append("\r\n") .append("bookNamePlaceholder=").append(bookNamePlaceholder).append("\r\n") .append("appName=").append(appName).append("\r\n") .append("env=").append(env).append("\r\n") //从eniroment中获取属性值 .append("env=").append(env.getProperty("book.name.placeholder")).append("\r\n"); returnsb.toString(); } }

来源:https://blog.csdn.net/hry2015/article/details/72353994

本文内容总结:@Value注入,不通过配置文件的注入属性的情况,通过配置文件的注入属性的情况,

原文链接:https://www.cnblogs.com/wangbin2188/p/9014837.html