配置文件如下:
代码语言:javascript复制server.port=8081person.name=孙超person.age=22person.birth=2022/12/12person.map.k1=k1person.list=a,bc,cperson.dog.name=xiaogouperson.dog.age=2
@Value 获取配置文件的值
代码语言:javascript复制package com.sunchao.demo.bean;import org.springframework.beans.factory.annotation.Value;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.stereotype.Component;import org.springframework.validation.annotation.Validated;import javax.validation.constraints.Email;import java.util.Date;import java.util.List;import java.util.Map;/** * @author sunyc * @create 2022-04-24 9:43 *///将配置文件中的值映射到person中//@ConfigurationProperties 告诉springboot将本类中的所有属性与配置文件中相关的属性配置//这个组件是容器中的组件,才能提供功能加@Component注解@Component//@ConfigurationProperties(prefix = "person")@Validated//数据校验public class Person {//@Email@Value("${person.name}")//从properties配置文件中获取值String name;@Value("${person.age}") //从properties配置文件中获取值int age;@Value("${person.birth}")//从properties配置文件中获取值Date birth;Map<String,Object> map;Dog dog;List list;@Overridepublic String toString() {return "Person{" "name='" name ''' ", age=" age ", birth=" birth ", map=" map ", dog=" dog ", list=" list '}';}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public Date getBirth() {return birth;}public void setBirth(Date birth) {this.birth = birth;}public Map<String, Object> getMap() {return map;}public void setMap(Map<String, Object> map) {this.map = map;}public Dog getDog() {return dog;}public void setDog(Dog dog) {this.dog = dog;}public List getList() {return list;}public void setList(List list) {this.list = list;}}
4、@PropertySource&@ImportResource&@Bean
@PropertySource:加载指定的配置文件;
使用配置类的方式给IOC容器中添加组件,不用xml的配合方式
收藏 | 0点赞 | 0打赏