mapProps) { this.mapProps = mapProps; }}通过依赖注⼊就可以获取该对象:
@Autowired
private YmlConfig config;
⽅法内获取值:
ObjectMapper objectMapper = new ObjectMapper();//测试加载yml⽂件
System.out.println(\"simpleProp: \" + config.getSimpleProp());
System.out.println(\"arrayProps: \" + objectMapper.writeValueAsString(config.getArrayProps()));System.out.println(\"listProp1: \" + objectMapper.writeValueAsString(config.getListProp1()));System.out.println(\"listProp2: \" + objectMapper.writeValueAsString(config.getListProp2()));System.out.println(\"mapProps: \" + objectMapper.writeValueAsString(config.getMapProps()));
(⼆)properties配置⽂件:
使⽤@PropertySource注解加载配置⽂件,该注解⽆法加载yml配置⽂件。使⽤@Value注解获得⽂件中的参数值
package com.sun.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
/**
* 加载properties配置⽂件,在⽅法中可以获取
* abc.properties⽂件不存在,验证ignoreResourceNotFound属性 * 加上encoding = \"utf-8\"属性防⽌中⽂乱码,不能为⼤写的\"UTF-8\" * Created by sun on 2017-3-30. */
@Configuration
@PropertySource(value = {\"classpath:/config/propConfigs.properties\ ignoreResourceNotFound = true,encoding = \"utf-8\")public class PropConfig {
// PropertySourcesPlaceholderConfigurer这个bean, // 这个bean主要⽤于解决@value中使⽤的${…}占位符。 // 假如你不使⽤${…}占位符的话,可以不使⽤这个bean。 @Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); }
}
//获取properties⽂件参数值有两种⽅法,⼀种获得Environment 的对象,第⼆种就是@Value注解@Autowired
private Environment env; @Value(\"${age}\") String name;
@RequestMapping(\"/\") @ResponseBody
String home(HttpServletRequest req) throws JsonProcessingException, UnsupportedEncodingException { logger.info(\"测试通过\");
ObjectMapper objectMapper = new ObjectMapper(); //测试加载yml⽂件
System.out.println(\"simpleProp: \" + config.getSimpleProp());
System.out.println(\"arrayProps: \" + objectMapper.writeValueAsString(config.getArrayProps())); System.out.println(\"listProp1: \" + objectMapper.writeValueAsString(config.getListProp1())); System.out.println(\"listProp2: \" + objectMapper.writeValueAsString(config.getListProp2())); System.out.println(\"mapProps: \" + objectMapper.writeValueAsString(config.getMapProps())); //测试加载properties⽂件
System.out.println(env.getProperty(\"name\"));//孙凯 System.out.println(env.getProperty(\"abc\"));//null System.out.println(name);//26 return \"Hello World!\"; }
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。