Spring @Value 使用
来源:互联网 发布:js 实现bind 编辑:程序博客网 时间:2024/05/22 04:26
昨天看到项目里一个Config类,加载一个properties文件,通过IO流去读取并加载到Property类里,感觉太过复杂,印象中有Spring @Value标签可以使用,就研究了一下。
目的:使用@Value来注入配置在properties文件中的key-value,使用@Value必须是托管在spring ioc容器中的bean
方法:你可以直接使用@Value注入全局变量,也可以注入setter方法
碰到的问题:我在注入controller类的时候,注入失败,注入其它类可以,原因是没有在web.xml->Spring的DispatcherServlet->contextConfigLocation指定的xml中配置PropertySourcesPlaceholderConfigurer
相关代码:
xml:
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:spring_*.properties</value> </list> </property> <property name="ignoreUnresolvablePlaceholders" value="true"/> </bean>
也可以使用@Configurable @PropertySource,来使用一个配置类替换XML
package com.smith.config;import org.springframework.beans.factory.annotation.Configurable;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.PropertySource;import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;import org.springframework.stereotype.Component;@Configurable@PropertySource("classpath:spring_test.properties") public class SmithConfig {}
Properties:在Maven项目下resource下建一个spring_开头的properties文件
Controller类:
package com.smith.controller;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Import;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import com.smith.config.SmithConfig;@Controller@RequestMapping("/helloSmith")@Import(SmithConfig.class)public class PropertyController {@Value("${abc}") private String abc;/*@Autowired private SmithConfig config;*/@RequestMapping(value="/showProperty", method = { RequestMethod.POST, RequestMethod.GET }) public void showCardNoPage() {System.out.println(abc); }}
0 0
- Spring @Value 使用
- Spring @Value使用示例
- Spring 3使用@Value
- Spring @Value注解的使用
- spring boot使用@Value,@PropertySource注解使用
- Spring中Value注解的使用
- Spring中Value注解的使用
- 使用spring 的注解 @value使用方法
- Spring @Value注解使用${}进行注入
- Spring注解中使用表达式@Value
- spring 中 @value 注解的使用
- JAVA学习之Spring @Value使用
- spring使用注解@Value读取.properties文件
- spring boot中使用@Value注解
- 首篇--spring使用@value注入静态变量
- spring @value
- Spring-@Value
- Spring Boot系列 Spring @Value 属性注入使用总结一
- 用户从键盘输入月份,使用switch语句输出该月份的天数
- MySQL优化-----从最简单的语句优化开始
- 【机器学习】关联规则与FP-Tree
- 报错std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::
- 彻底理解webservice SOAP WSDL
- Spring @Value 使用
- android:theme
- Java之POJO(转)
- Cocoapods pod update 报错
- dynamic_cast123
- 创业者都是抑郁症患者,任正非、张朝阳、徐小平、毛大庆,是这样挺过来的
- 极化SAR一些常用知识总结(不断更新中)
- 使用jetty时报503的错误的解决
- Weblogic10 与 Websphere MQ7集成方案[2]