properties、yml配置文件映射对象

1、properties文件内容映射到类对象(属性),如Resource目录下的1.properties文件已配置前缀为com.imooc.people相关的信息,然后:
pom添加依赖:springboot-configuration-processor
People类对象上方添加注解:
@Configuration
@PropertySource(value="classpath:1.properties")      //指定从哪个properties读取内容
@ConfigurationProperties(prefix="com.imooc.people")    //指定读取的前缀
public class{
  private String name;
  private String age;
。。。name、age的getter/setter。。。
}
然后直接在controller中@Autowired可直接获取到有属性值的People对象

2、yml文件内容映射到类对象(属性),yml 格式不支持 @PropertySource 注解导入,一般用@Value。如Resource目录下的1.properties文件已配置前缀为com.imooc.people相关的信息,然后:
@Configuration      //或者@Component
public class{
  @Value("${com.imooc.people.name}")
  private String name;
  @Value("${com.imooc.people.age:#{null}}")    //age取不到对应配置值时,采用默认值null赋值
  private String age;
。。。name、age的getter/setter。。。
}

猜你喜欢

转载自www.cnblogs.com/afei1759/p/12099449.html