1、利用spring lnitailizr 快速创建一个springboot项目
2、导入相关依赖
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--此依赖可要可不要,作用就是编写yml文件有代码提示--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</art <optional>true</optional> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
3、编写两个基本bean
@Component // 注入容器 @Data // get ,set方法 @ToString // toString方法 @AllArgsConstructor // 有参构造 @NoArgsConstructor // 无参构造 public class Dog { private String name; private int age; }
@Component @Data @ToString @NoArgsConstructor @AllArgsConstructor @ConfigurationProperties(prefix = "com.lili") public class Person { private String name; private Boolean man; private Date birth; private Integer age; private Dog dog; private String[] hobby; private List<String> books; private Map<String,Object> grade; private Set<Double> height; private Map<String,List<Dog>> allDogs; }
4、编写yml文件,对属性进行赋值
com: lili: name: "张三" man: true birth: 1999/12/10 age: 12 dog: name: "欢欢" age: 12 hobby: - "篮球" - "足球" - "排球" books: ["人性的弱点","Java8实战"] grade: math: 20 english: 100 height: [12.21,12] all-dogs: ill: - {name: "小兰",age: 12} - name: "小花" age: 12 health: - { name: 'lili',age: 12 } - name: "花花" age: 12
5、编写测试类进行访问
@SpringBootTest class Springboot02ApplicationTests { @Autowired Person person; @Test void contextLoads() { System.out.println(person); } }
6、运行结果
Person(name=张三, man=true, birth=Fri Dec 10 00:00:00 CST 1999, age=12, dog=Dog(name=欢欢, age=12), hobby=[篮球, 足球, 排球], books=[人性的弱点, Java8实战], grade={math=20, english=100}, height=[12.21, 12.0], allDogs={ill=[Dog(name=小兰, age=12), Dog(name=小花, age=12)], health=[Dog(name=lili, age=12), Dog(name=花花, age=12)]})