SpringBoot中自定义配置类
1.方式一:
配置类标注:
- @ConfigurationProperties注解,可以设置前缀名
- @Component 将该类放入spring容器中
- 必须设定get/set方法
配置类:
@Component //将该Bean放入spring容器中
@ConfigurationProperties(prefix = "com.example")//指定该类为配置获取类,并指定前缀
public class MyConfig {
private String name;
private Integer age;
//必须设置get set方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
application.properties中配置
com.example.age=20
com.example.name=xxx
使用:
在其他Bean中可以直接注入该Bean
@RestController
public class DemoController {
@Autowired
private MyConfig config;
@GetMapping("/demo2")
public String m2(){
return config.getName();
}
}
2.方式二
配置类:
不使用 @Component 将该类放入spring容器中,而是使用@EnableConfigurationProperties(MyConfig.class)在根配置类中引入
@ConfigurationProperties(prefix = "com.example")//指定该类为配置获取类,并指定前缀
public class MyConfig {
private String name;
private Integer age;
//必须设置get set方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
@SpringBootApplication
@EnableConfigurationProperties(MyConfig.class) //引入自定义配置类
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class,args);
}
}
本文介绍了在SpringBoot中自定义配置类的两种方法。第一种方法是使用@ConfigurationProperties注解并配合@Component,设置前缀,并确保提供get/set方法。配置项在application.properties中定义,可在其他Bean中直接注入。第二种方法则是不使用@Component,而是直接在根配置类中引入配置类。
4416

被折叠的 条评论
为什么被折叠?



