在SpringBoot中可以把bean的属性放在yaml配置文件中,如下:
cat:
name: tom
age: 12
food:
- fish
- chicken
pom.xml导依赖:
导入configuration-processor
之后,以后在配置文件里写配置时就会有自动提示。这个依赖对业务没有任何影响,只是为了开发方便,所以我们在打jar包的时候应该将其排除,避免最终的jar包里类太多。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<!--以下是添加的配置-->
<configuration>
<excludes>
<exclude>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
yaml(也可写成yml)的具体语法这里不作展开,主要记录一下在SpringBoot中怎么用yml配置文件来配置一个bean的属性。
application.yml
的优先级低于application.properties
,所以在.properties中的配置会先于.yml中的配置生效
先配置一个Cat
的实体类,并用@Component
来注册bean,但未对其属性进行装配:
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
@ConfigurationProperties(prefix = "cat")
@Component
public class Cat {
private String name;
private int age;
private List<String> food;
}
注意:待装配的实体类必须要有
set
方法,否则使用配置文件来装配bean的方式不会生效,lombok
下的@Data
会自动生成set
方法。
对应的application.yml
:
cat:
name: tom
age: 12
food:
- fish
- chicken
再写一个controller来测试能否返回Cat
的实体类(通过JSON传递):
package com.zzw.springboot_01_demo.controller;
import com.zzw.springboot_01_demo.bean.Cat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@Autowired
private Cat cat;
@RequestMapping("/cat")
public Cat getCat() {
return cat;
}
}
这里用到@Autowire
来自动从容器中寻到class是Cat
的bean并自动装配
结果,访问localhost:8080/cat
:
版权声明:本文为weixin_43146572原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。