Spring的@PropertySource和@Value注解例子
来源:互联网 发布:鲁大师linux版 编辑:程序博客网 时间:2024/05/24 15:37
原文链接:http://9leg.com/spring/2015/02/12/spring-propertysource-value-annotations-example.html?utm_source=tuicool&utm_medium=referral
在这篇文章中,我们会利用Spring的 @PropertySource 和 @Value 两个注解从配置文件properties中读取值,以及如何从配置文件中的值转换为List对象。
创建Spring配置Class
@Configurable@ComponentScan(basePackages = "com.9leg.java.spring")@PropertySource(value = "classpath:spring/config.properties")public class AppConfigTest { @Bean public PropertySourcesPlaceholderConfigurer propertyConfigInDev() { return new PropertySourcesPlaceholderConfigurer(); } }
通过 @PropertySource 注解将properties配置文件中的值存储到Spring的 Environment 中,Environment接口提供方法去读取配置文件中的值,参数是properties文件中定义的key值。上面是读取一个配置文件,如果你想要读取多个配置文件,请看下面代码片段:
@PropertySource(value = {"classpath:spring/config.properties","classpath:spring/news.properties"})
在Spring 4版本中,Spring提供了一个新的注解—— @PropertySources ,从名字就可以猜测到它是为多配置文件而准备的。
@PropertySources({@PropertySource("classpath:config.properties"),@PropertySource("classpath:db.properties")})public class AppConfig {//something}
另外在Spring 4版本中, @PropertySource 允许忽略不存在的配置文件。先看下面的代码片段:
@Configuration@PropertySource("classpath:missing.properties")public class AppConfig {//something}
如果missing.properties不存在或找不到,系统则会抛出异常 FileNotFoundException 。
Caused by: java.io.FileNotFoundException: class path resource [missiong.properties] cannot be opened because it does not exist
幸好Spring 4为我们提供了 ignoreResourceNotFound 属性来忽略找不到的文件
@Configuration@PropertySource(value="classpath:missing.properties", ignoreResourceNotFound=true)public class AppConfig {//something}
@PropertySources({@PropertySource(value = "classpath:missing.properties", ignoreResourceNotFound=true),@PropertySource("classpath:config.properties") })
最上面的AppConfigTest的配置代码等于如下的XML配置文件
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <context:component-scan base-package="com.9leg.java.spring"/> <bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer"><property name="ignoreUnresolvablePlaceholders" value="true"/><property name="locations"> <list> <value>classpath:spring/config.properties</value> </list></property> </bean></beans>
创建properties配置文件
server.name=9leg,springserver.id=10,11,12server.jdbc=com.mysql.jdbc.Driver
创建一个简单的服务
@Component(value = "mockConfigTest")public class MockConfigTest {@Value("#{'${server.name}'.split(',')}")private List<String> servers;@Value("#{'${server.id}'.split(',')}")private List<Integer> serverId;@Value("${server.host:127.0.0.1}")private String noProKey;@Autowiredprivate Environment environment;public void readValues() {System.out.println("Services Size : " + servers.size());for(String s : servers)System.out.println(s);System.out.println("ServicesId Size : " + serverId.size());for(Integer i : serverId)System.out.println(i);System.out.println("Server Host : " + noProKey);String property = environment.getProperty("server.jdbc");System.out.println("Server Jdbc : " + property);}public static void main(String[] args) {AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(AppConfigTest.class);MockConfigTest mockConfigTest = (MockConfigTest) annotationConfigApplicationContext.getBean("mockConfigTest");mockConfigTest.readValues();}}
首先使用 @Component 注解声明,接着就是属性字段上的 @Value 注解,但在这里比较特殊,是通过 split() 方法,将配置文件中的9leg,spring分割后组成list对象。心细的同学可能注意到了 server.host 这个key并不存在配置文件中。是的,在这里使用的是默认值,即127.0.0.1,它的格式是这样的。
@value("${key:default}")private String var;
然后注入了 Environment ,可以通过 getProperty(key) 来获取配置文件中的值。 运行main方法,来看下输出结果:
Services Size : 29legspringServicesId Size : 3101112Server Host : 127.0.0.1Server Jdbc : com.mysql.jdbc.Driver
最后要说一点,在main方法中请使用 new AnnotationConfigApplicationContext(AppConfigTest.class) 来代替 new ClassPathXmlApplicationContext(“applicationContext.xml”) 或者 new FileSystemXmlApplicationContext(“src/main/resources/applicationContext.xml”) 。
- Spring的@PropertySource和@Value注解例子
- Spring的@PropertySource和@Value注解例子
- Spring的@PropertySource和@Value注解例子
- Spring 4 @PropertySource和@Value注解示例
- Spring 4 @PropertySource和@Value注解示例
- spring boot使用@Value,@PropertySource注解使用
- (15)spring boot使用@Value,@PropertySource注解使用
- spring注解 @PropertySource 配置数据源
- Spring @Value注解的使用
- Spring @Value注解的用法
- Springboot中PropertySource注解的使用
- spring@PropertySource
- spring注解 配置属性 Environment@PropertySource 配置数据源
- spring注解@PropertySource,给类注入属性文件
- spring 3中新增的@value注解
- spring 3中新增的@value注解
- Spring中Value注解的使用
- spring 3中新增的@value注解
- 美团Android资源混淆保护实践
- ssh普通用户(非root用户)的密钥登录
- Linux LVM安全删除硬盘或分区-
- 文字复制到剪贴板
- 腾讯,阿里等面试题(一)
- Spring的@PropertySource和@Value注解例子
- RecyclerView框架使用详解
- Java基础再回首之设计模式系列①-----StrategyPattern 策略者模式(案列教程,附带demo)
- 经验谈|如何处理好产品与开发的关系
- 如何将大规模数据导入Neo4j
- 解决MySQL别名重命名不起作用的问题
- Oracle-Replace使用小结
- 给Java新手的一些建议----Java知识点归纳(Java基础部分)
- SSH环境搭建出现NullPointerException