- 配置文件
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);
}
}
- 運行結果如下
完成!