1.@Value注解作用
该注解的作用是将我们配置文件的属性读出来,有@Value(“${}”)和@Value(“#{}”)两种方式。
2.@Value注解作用的两种方式
场景
假如有以下属性文件dev.properties, 需要注入下面的tager
第一种方式@Value(“${}”):
server.port=8000
通过PropertyPlaceholderConfigurer
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="dev.properties" /> </bean>
代码
@Value("${server.port}") private String tag;
项目一旦运行,private String tag属性的值就会被赋值为8000
第二种方式 @Value(“#{}”):
通过PreferencesPlaceholderConfigurer
<bean id="appConfig" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer"> <property name="location" value="dev.properties" /> </bean>
代码:
@Value("#{config['server.port']}") private String tag;
项目一旦运行,private String tag属性的值也会被赋值为8000
2.@Value注解作用的其他方式
(1)常量注入
@Value("normal")
private String normal; // 注入普通字符串
@Value("classpath:com/hry/spring/configinject/config.txt")
private Resource resourceFile; // 注入文件资源
@Value("http://www.baidu.com")
private Resource testUrl; // 注入URL资源
参考网址:https://www.cnblogs.com/rain-in-summer/p/7382003.html
https://blog.csdn.net/woheniccc/article/details/79804600
https://www.cnblogs.com/bclshuai/p/10309119.html