SpringBoot

SpringBoot 获取属性的3种方式

2018-04-23  本文已影响57人  当当一丢丢

主题

1. 绑定属性的方式

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 文件中的属性

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;

}

上述均可通过如下方法验证

@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;
    }

}

http://blog.csdn.net/yingxiake/article/details/51263071

上一篇 下一篇

猜你喜欢

热点阅读