springboot中配置类读取配置文件application.properties内容

两种:
第一种:只对Book.java中增加注解
举例:
application.properties


book.brand=九阳神功
book.price=100000
@Component  // 只有在容器中的组件才能拥有springboot的强大功能
@ConfigurationProperties(prefix = "book")
public class Book{
    private String brand;
    private Integer price;
}

HelloController.java

@RestController
public class HelloController {

    @Autowired
    Book book;

    @RequestMapping("/book")
    public Book book(){
        return book;
    }
}

访问请求:localhost:8080/book 会显示响应配置文件中的内容。

第二种:
Book.java中增加注解

@ConfigurationProperties(prefix = "book")

配置类 MyConfig.java中增加注解:

@EnableConfigurationProperties(Book.class)  

举例:
application.properties


book.brand=九阳神功
book.price=100000

Book.java

@Data
@ToString
@ConfigurationProperties(prefix = "book")
public class Book{

    private String brand;

    private Integer price;

    /**
     * 1.
     * @Component  // 只有在容器中的组件才能拥有springboot的强大功能
     * @ConfigurationProperties(prefix = "book")
     *
     * 2.
     * @ConfigurationProperties(prefix = "book")
     * 配置类中增加
     * @EnableConfigurationProperties(Book.class)
     */
}

配置类 MyConfig.java

@Configuration(proxyBeanMethods = true)
@ImportResource("classpath:beans.xml")  // 使用xml注入相关bean,如果其它方式注入,可以注释该行
@EnableConfigurationProperties(Book.class)  
/**
 * 1.开启Bar配置绑定功能
 * 2.把这个Book组件自动注册到容器中
 */
public class MyConfig {}

优点:@EnableConfigurationProperties(Book.class) 此注解,可以绑定配置已经存在的jar包中的已存在类。

相关推荐

  1. springboot使用@value读取配置

    2024-04-23 04:58:03       12 阅读
  2. Spring 使用@Value注解读取配置文件的数组

    2024-04-23 04:58:03       38 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-23 04:58:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-23 04:58:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-23 04:58:03       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-23 04:58:03       20 阅读

热门阅读

  1. MySQL-知识点详解

    2024-04-23 04:58:03       15 阅读
  2. Beego框架学习

    2024-04-23 04:58:03       15 阅读
  3. webSocket + springboot+vue3用法

    2024-04-23 04:58:03       13 阅读
  4. android wifi直连 wifip2pmanager

    2024-04-23 04:58:03       12 阅读
  5. 爬虫f12跳转和debugger检测

    2024-04-23 04:58:03       12 阅读
  6. C#面:如何避免类型转换时的异常?

    2024-04-23 04:58:03       14 阅读
  7. 网络安全之痕迹清理

    2024-04-23 04:58:03       15 阅读