栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【SpringBoot注解】@ConfigurationProperties注解

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【SpringBoot注解】@ConfigurationProperties注解

@ConfigurationProperties主要作用就是将prefix属性指定的前缀配置项的值绑定到这个Bean上,默认情况下需要和@Component或者@Configuration一起使用才能生效。

首先回忆以下使用Java如何读取properties文件中的内容,会看到使用起来会很麻烦,SpringBoot给我们提供了更简单的方式读取Properties配置项内容。

public class getProperties {
     public static void main(String[] args) throws FileNotFoundException, IOException {
         Properties pps = new Properties();
         pps.load(new FileInputStream("a.properties"));
         Enumeration enum1 = pps.propertyNames();//得到配置文件的名字
         while(enum1.hasMoreElements()) {
             String strKey = (String) enum1.nextElement();
             String strValue = pps.getProperty(strKey);
             System.out.println(strKey + "=" + strValue);
             //封装到JavaBean。
         }
     }
 }
方式一

当配置文件中有前缀为mycar的配置内容时,会自动将其注入组件中

注意:只有在容器中的组件,才会拥有SpringBoot提供的强大功能,所以添加了@Component注解
@Data
@Component
@ConfigurationProperties(prefix = "mycar")
public class Car {
    private String brand;
    private Integer price;

}

application.properties配置内容

mycar.brand=BYD
mycar.price=100000

通过controller层获取对象

RestController
public class HelloController {

    @Autowired
    Car car;
    @RequestMapping("/car")
    public Car car(){
        return car;
    }
}

成功注入对象里面 

 

方式二

场景:如果我们使用的是第三方jar包,就不能自己添加@Component注解,需要使用新的方式

@Data
@ConfigurationProperties(prefix = "mycar")
public class Car {
    private String brand;
    private Integer price;

}

 @EnableConfigurationProperties有两个作用:

  • 开启Car配置绑定功能
  • 把这个Car组件自动注入到容器中
@Configuration
@EnableConfigurationProperties(Car.class)
public class MyConfig {
}

 

暑期编程PK赛 得CSDN机械键盘等精美礼品!
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1017462.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号