Spring Boot 入门知识

来源:互联网 发布:开票软件双击打不开 编辑:程序博客网 时间:2024/06/10 11:44

新建项目

  • 通过idea 中新建Spring Initializr来新建,如提示无法连接 https://start.spring.io ,将https改成http即可。
  • 填写项目基本的信息
  • 选择SpringBoot的版本与SpringBoot的组件
  • 第一交新建SpringBoot需要下载

启动项目

  1. 直接在项目生成时自动创建的类中右击“run”
  2. 通过命令行,进入项目目录执行命令:mvn spring-boot:run
  3. 通过命令行。mvn install 编译项目,cd target 进入target文件夹执行:java -jar [target中生成的.jar文件]

配置

配置文件

配置文件默认为resources目录下 的application.properties。我们在这个文件中添加两项配置:

#将服务器端口号改成8081server.port= 8081#设置url前缀为 /boot server.context-path= /boot

此时我们启动项目发现原来的地址访问不了了。我们将端口改成8081,路径改成 /boot/hello就可以访问了

推荐

推荐将配置文件改成 application.yml 配置写起来会更简洁,如下:

server:  port: 8081  context-path: /boot

需要注意的是 .yml 配置时冒号后必须有一个空格才能被识别

配置属性

  • 配置属性注入

可以在配置文件中指定值,在类中通过注解@Value 定义变量,SpringBoot会帮我们自动把配置中的值注入到变量中

配置

server:  port: 8080  context-path: /bootcupSize: C

    @Value("${cupSize}")    private String cupSize;    @RequestMapping(value = "/hello",method = RequestMethod.GET)    public String myHello(){        return cupSize;    }

输出

    C
  • 在配置中再使用当前配置

配置

server:  port: 8080  context-path: /bootcupSize: Cage: 18context: "cupSize: ${cupSize}, age: ${age}"

@Value("${cupSize}")    private String cupSize;    @Value("${age}")    private String age;    @Value("${context}")    private String context;    @RequestMapping(value = "/hello",method = RequestMethod.GET)    public String myHello(){        return context;    }

输出

    cupSize: C, age: 18
原创粉丝点击