zoukankan      html  css  js  c++  java
  • 微服务之springboot 自定义配置(一)Application配置文件

    配置的文件的格式

    springboot可以识别两种格式的配置文件,分别是yml和properties 文件。我们可以将application.properties文件换成application.yml,这两个文件都可以被SpringBoot自动识别并加载,但是如果是自定义的配置文件,就最好还是使用properties格式的文件,因为SpringBoot中暂时还并未提供手动加载yml格式文件的功能(这里指注解方式)。

    yml 配置文件 属性格式:配置的属性和属性值要有空格隔开。没有空格报:java.lang.IllegalArgumentException: Could not resolve placeholder 'my.name' in value "${my.name}"

    server :
      port : 8888
    my :
      name : forezp
      age : 12

    propreties文件  格式要求:

    server.port=8888
    my.name=forezp
    my.age=12

    application.properties配置文件欲被SpringBoot自动加载,需要放置到指定的位置:src/main/resource目录下,一般自定义的配置文件也位于此目录之下。

    application.properties配置文件是在SpringBoot项目启动的时候被自动加载的,其内部的相关设置会自动覆盖SpringBoot默认的对应设置项,所以的配置项均会保存到Spring容器之中。

    公共配置文件自定义属性

    1 server.port=8888
    2 my.name= forezp
    3 my.age=12

    @RestController 访问属性类

    package com.forezp.appConfig;
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class MiyaController {
        @Value("${my.name}")
        private String name;
        @Value("${my.age}")
        private int age;
    
        @RequestMapping("/hah")
        public String hah(){
            return name+" :   "+age;
        }
    }

    运行springboot项目 ,运行成功 浏览器输入网址:http://localhost:8888/hah

     springboot 启动类设置扫描包文件这里只是提下

     浏览器访问网址报404错误,如下:

     直接报404错误,最后检查了springboot 启动类

    package com.forezp.helloworld;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @SpringBootApplication
    @RestController
    
    public class HelloWorldApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(HelloWorldApplication.class, args);
    
        }
        @GetMapping("/hi")
        public String  hi (){
            return "hi  I'am forezp";
        }
    }

    最后才弄清楚:启动类和对应的RestController类不在同一包下  。需要在启动类上方添加@ComponentScan注解扫描com.forezp.appConfig 包下的文件

    Spring Boot只会扫描启动类当前包和以下的包 ,就是说现在我启动类的包是在com.forezp.helloworld下面,然后他就只会扫描com.forezp.helloworld或者com.forezp.helloworld.*下面所以的包,所以我的Controller在com.forezp.appConfig包下面Spring Boot就没有扫描到。

    把controller类放到com.forezp.helloworld下面就好了

  • 相关阅读:
    野指针防范
    Linuxgate.so.1的含义[ZZ]
    malloc hook
    用PDF补丁丁一分钟批量删除PDF文档的第一页和最后一页
    PDF 补丁丁 0.4 测试版已经上线
    生活小百科:实用的生活保健小窍门,60则!....
    Pascal Analyzer 4 代码分析使用简要说明
    大数法则
    make: *** No rule to make target `all'. Stop.
    界面动态配置:持久化反持久化
  • 原文地址:https://www.cnblogs.com/shaoxiaohuan/p/10463546.html
Copyright © 2011-2022 走看看