在開發過程中,我們時常需要在項目啓動的時候就能獲取到某一個類,這時我們只需要添加一個配置類即可,在這個配置類上面添加上@Configuration,加上這個註解後就可以將當前的這個類標註爲一個配置類,那麼在項目啓動的時候就會直接去加載這個類。
並且我們還可以在配置類中直接去獲取到yml配置文件中的數據,直接使用@Value("${xxxx.xxxx")即可。
直接上demo:
編寫一個格式爲yml的配置文件,內容如下:
server:
port: 9001
創建一個是實體類:
public class User {
private String name;
private Integer age;
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;
}
}
在啓動類的同包下面創建名爲BeanConfig的配置類,在這個配置類中來獲取yml中的數據以及通過某一個方法來創建並返回我們需要的類:
@Configuration
public class BeanConfig {
@Value("${server.port}") //獲取yml文件中配置的端口號
private Integer port;
@Bean //此註解非常的關鍵,意爲創建一個該返回類型的對象
public User getInteger(){ //返回User對象
User user = new User();
user.setAge(port);
user.setName("xh");
return user;
}
}
基本工作準備完畢,下面我們編寫一個測試的Controller來測試一波,即看能不能將配置類中返回的對象直接注入到controller中,以及看能不能在配置類中獲取到yml文件中的數據:
@RestController
public class BeanController {
@Autowired
private User user;
@RequestMapping("getPort")
public User getPort(){
user.setName(user.getName()+"111111");
return user;
}
}
因爲我們在配置類中已經將獲取的端口號port字段作爲了user對象的age,然後設置了user對象的name字段值爲“xh”,如果能在controller中注入user對象,我們就將注入進來的user對象的name字段的name值拼接“11111”,那麼最終返回的值應爲{“name”:“xh111111”,“age”:9001}
下面我們就來訪問接口測試一波:
數據正確,說明上面的配置類的方式是正確的
在這裏記錄一下,以防後面忘記了可以方便查閱