手寫一個spring boot properties類型安全以及自動裝配bean

  • 配置文件
zx.name ="zhengxiang"
zx.age = 18
zx.sex = "male"
  • 增加類型安全的配置java文件,代碼如下:
Data
@AllArgsConstructor
@NoArgsConstructor
@ConfigurationProperties(prefix = "zx")
public class Student {
    private String name;
    private Integer age;
    private String sex;
}
  • 增加自動裝配類
@Configuration
@EnableConfigurationProperties(Student.class)
@Slf4j
public class StudentConfig {
    @Bean
    public Zheng create(Student student){
        log.info(">>>>>>>>>>>> init student start");
        Zheng zheng = new Zheng();
        zheng.setAge(student.getAge());
        zheng.setName(student.getName());
        zheng.setSex(student.getSex());
        log.info(">>>>>>>>>>>> init student success:{}",zheng.toString());
        return zheng;
    }
}
  • 增加配置啓用開關注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(StudentConfig.class)
public @interface EnableAutoCreate {
}
  • 想要初始化的類
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Zheng {
    private String name;
    private Integer age;
    private String sex;
}
  • 在啓動類上加上註解
@SpringBootApplication
@EnableAutoCreate
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}
  • 運行結果如下
    在這裏插入圖片描述

完成!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章