主题
- 绑定属性的方式
- 直接绑定 application.properties 文件中的属性
- 如何绑定 其他文件中的属性
1. 绑定属性的方式
- autowire 注入 Environment bean //获取属性的方式,env.getProperties("city.address")
- @Value("${city.address}"") //绑定属性的方式,绑定到某些类上,再使用,用于对属性分门别类
2. 直接绑定 application.properties 文件中的属性
pplication.properties 文件中定义
car.field.color=black
car.field.brand=benz
定义 CarProperty 类
- 方法一
@Component //绑定到的property 类首先需要成为一个bean,@Value 实际上是 @BeanPostProcessor 的处理
@Data //添加get/set, intellj lombak插件支持
public class CarProperty {
@Value("${car.field.color}") //直接绑定
private String color;
@Value("#{car.field.brand}")
private String brand;
}
- 方法二
@Component //标志为上下文bean, 此处也可不写,但需要在 @EnableConfigurationProperties 指定参数 CarProperty 类
@ConfigurationProperties(prefix = "car.field") //以前缀的形式 将各种属性 分门别类 与相应类 一一对应
@Data
public class CarProperty {
private String brand;
private String color;
}
开启ConfigurationProperties功能
@SpringBootApplication
//开启configurationProperties,@Value 不需此行注解,
//@EnableConfigurationProperties(CarProperty.class) //可添加参数,作用是 注入该类bean,此刻无需 @Component 修饰 CarProperty 类
//即,@Component 和 @EnableConfigurationProperties(CarProperty.class)的作用是一样的,都是使 CarProperty 成为上下文一个 Bean, 只是注解到到的位置不一样,取其一即可
public class MainApplication {
public static void main(String[] args){
SpringApplication.run(MainApplication.class, args);
}
}
3. 绑定 car.properties 文件中的属性
- 前面,默认的属性文件为 application.properties, 现在我们尝试读取自定义property 文件
- 达到这种效果,必须使用 ConfigurationProperties 这种形式,@Value 够呛
- 还有一点注意,当使用 @PropertySource 注解时,尽量使用@Component来生成 bean, 通过 @EnableConfigurationProperties 不起作用
resources 目录创建car.properties 文件
car.field.color=black
car.field.brand=benz
创建property属性文件
@Component //此时,务必使用 @Component
@ConfigurationProperties(prefix = "car.field") //前缀不变
@PropertySource(value="classpath:car.properties") // 限定属性存在的 属性文件,若没有此注解则为 application.properties 文件,且value 不能为空
@Data
public class CarProperty {
private String brand;
private String color;
}
上述均可通过如下方法验证
- 创建 CarController
@RestController
@RequestMapping("/car")
@Slf4j
public class CarController {
@Autowired
private CarProperty carProperty;
@RequestMapping(value = "/property", method = RequestMethod.GET)
public String testProperty() {
String name = carProperty.getColor();
log.info("color: " + name);
return "color: " + name;
}
}