美文网首页
springboot之属性注入

springboot之属性注入

作者: sunpy | 来源:发表于2023-01-26 23:55 被阅读0次

    单个属性注入

    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;
    }
    

    相关文章

      网友评论

          本文标题:springboot之属性注入

          本文链接:https://www.haomeiwen.com/subject/agishdtx.html