Spring Boot核心-自定义类配置
1.常规属性自定义
在常规Spring 环境中我们注入properties文件里的属性值,需要通过@PropertySource指明properties文件位置,然后通过@Value注入,Spring Boot环境下则简化了很多,只需在application.yml中添加属性,使用时直接使用@Value注入。
application.yml
lwsi:
name: lwsi
version: 1.0
copyRightYear: 2019
使用方法:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class IndexController {
@Value("${lwsi.name}")
private String name;
@Value("${lwsi.version}")
private String version;
@Value("${lwsi.copyRightYear}")
private String copyRightYear;
public void testDemo(){
System.out.println("name:"+name+",version:"+version+",copyRightYear:"+copyRightYear);
}
@RequestMapping("index")
public String index(){
testDemo();
return "Hello,Spring Boot! ";
}
实际项目使用过程中,如果被多个地方调用,会需要注入很多次,这样会比较麻烦。Spring Boot提供另外一种注入方法来解决这种问题,通过@ConfigurationProperty将properties属性注入到一个bean中并绑定bean属性,下次调用properties属性时,可以直接注入对应的bean。此种配置方式为类型安全配置
2.基于properties类型安全配置
学过java的都知道请求参数过多的时候可以将参数封装成对象,直接将对象作为入参。此种方式也是同样的方式,将所有属性封装成一个对象,对象属性绑定properties属性(名称相同)并通过@ConfigurationProperty注解绑定前缀和properties文件路径,此类必须在SpringBoot的扫描路径下。封装对象bean代码:
package com.bwl.chapter01.com.bwl.model;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "lwsi")
public class LwsiConfig {
private String name;
private String version;
private String copyRightYear;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getCopyRightYear() {
return copyRightYear;
}
public void setCopyRightYear(String copyRightYear) {
this.copyRightYear = copyRightYear;
}
}
使用方法:
package com.bwl.chapter01.com.bwl.controller;
import com.bwl.chapter01.com.bwl.model.LwsiConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class IndexController {
@Autowired
private LwsiConfig config;
@RequestMapping("test")
public String config(){
return "项目名称:"+config.getName()+",项目版本号:"+config.getVersion()+"版权:"+config.getCopyRightYear();
}
运行界面结果: