springboot之属性注入
2023-01-26 本文已影响0人
sunpy
单个属性注入
application.yml
enterprise:
env: test
注入单个属性
@Slf4j
@RequestMapping("/test")
@RestController
public class TestController {
@Value("${enterprise.env}")
private String env;
@GetMapping("/doService")
public void doService() {
log.info("---------- env = " + env);
}
}
对象属性注入
application.yml
User:
username: zhangsan
age: 23
birth: 1990-09-12
注入对象属性:
@ToString
@Data
@ConfigurationProperties(prefix = "user")
@Component
public class UserVO {
private String username;
private Integer age;
private String birth;
}
@Slf4j
@RequestMapping("/test")
@RestController
public class TestController {
@Autowired
private UserVO userVO;
@GetMapping("/doService")
public void doService() {
log.info("---------- env = " + userVO);
}
}
属性注入校验
导包:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
@org.springframework.validation.annotation.Validated
@ToString
@Data
@ConfigurationProperties(prefix = "user")
@Component
public class UserVO {
@javax.validation.constraints.NotEmpty(message = "用户名不能为空")
private String username;
@javax.validation.constraints.NotNull(message = "年龄不能为空")
private Integer age;
private String birth;
}
说明:这里面的@Validated是必须要有的。
外部属性文件properties注入
user.username=lisi
user.age=25
user.birth=1991-09-12
@ConfigurationProperties(prefix = "user")
@PropertySource("classpath:file/user.properties")
@ToString
@Data
@Component
public class UserVO {
private String username;
private Integer age;
private String birth;
}