• Spring Boot . 4 -- 定制 Spring Boot 配置 【2】


         除了第一篇中使用 覆写的方式进行 自动配置的更改外,还可以通过 Spring Boot 中提供的 application.properties 文件改变应用的运行时配置。这种配置的方式粒度是非常精细的。

         application.properties

         在 Spring Boot 应用中,application.properties 文件在 resource/ 目录下,初始状态下,application.properties 是空白的。通过这个文件可以比较细粒度的控制Spring Boot 中的一些配置,比如 数据库链接、特定参数配置等。默认情况下,应用启动后监听的端口为 8080,如果想要将坚挺的端口设置为7000,那么只要在application.properties 文件中加上 server.port=7000,然后启动应用,在浏览器中 使用 localhost:7000 就可以访问页面了。

         application.properties 文件有一些默认的可配置参数,比如spring.datasource.* 可以使用这些配置,对应用中使用的DataSource进行配置。这些已有的配置可以通过文档查到。使用自主的配置与使用原有配置,方法基本是一致的。举个例子,如果想在一个类中使用application.properties 中配置的数据。需要使用注解 @ConfigurationProperties(prefix="test")

    @Controller
    @RequestMapping("/")
    @ConfigurationProperties(prefix = "test")
    public class ReadingListController {
    
         private String property;
        
         System.out.println("value" + property);
        
         public void setProperty(String property) {
            this.property=property;
         }
    }

        在 application.properties 中只要简单指定 属性的值:

    test.property=just a test

        当然,如果想要在代码中使用 application.properties 中的参数初始化一个类对象,在其他的地方直接以实例的方式使用也是非常好的。使用方式与上面基本是一致的。首先在application.properties 文件中定义需要的数据:

    dealer.item=ball
    dealer.fashion=true
    dealer.money=100
    dealer.home=shop

       定义一个类Dealer,使用当前定义的配置 :

    @ConfigurationProperties(prefix = "dealer")
    @Configuration
    public class Dealer { private String item; private boolean fashion; private int money; private String home; public String getItem() { return item; } public void setItem(String item) { this.item = item; } public boolean isFashion() { return fashion; } public void setFashion(boolean fashion) { this.fashion = fashion; } public int getMoney() { return money; } public void setMoney(int money) { this.money = money; } public String getHome() { return home; } public void setHome(String home) { this.home = home; } }

        Dealer 在Controller 中进行使用:

    @Controller
    public class HelloController {
    
        @Autowired
        private ReaderRepository readerRepository;
    
        private Dealer dealer;
    
        @Autowired
        public HelloController(Dealer dealer) {
            this.dealer = dealer;
        }
    
        @RequestMapping(value = "/prop")
        public String testProp()
        {
            System.out.println("HERE " + dealer.getHome());
            return "index";
        }
    }

        使用的套路基本上就是这样的。 

  • 相关阅读:
    java wait 与 notify sleep
    java线程安全总结
    ubuntu安装遇到的问题
    python时间处理函数
    js获取当前时间
    sql如何将同个字段不同值打印在一行
    django models数据类型
    django上传图片和文字记录
    django form使用学习记录
    django中request对象详解(转载)
  • 原文地址:https://www.cnblogs.com/tju-gsp/p/6291178.html
Copyright © 2020-2023  润新知