EchoDemo's Blogs

SpringBoot的第一个入门程序

1、在intellij idea2018上创建一个maven项目(在这里我使用的是apache-maven-3.3.9以及1.8版本的JDK)

"1"

"2"

"3"

"4"

2、打开main里面的GirlApplication文件,在同一个包下面新建一个HelloController.java文件并创建一个方法。

"打开GirlApplication.java文件"

"创建HelloController.java文件"

3、在GirlApplication.java文件中启动该项目。成功之后在浏览器当中输入127.0.0.1:8080/hello。

"在浏览器查看"

4、项目属性配置(创建配置文件和配置文件属性类)

"文件分布"

(1)生产、测试环境以及主配置文件内容

//测试环境内容
server:
  port: 8080
girl:
  cupSize: B
  age: 18

//生产环境内容
server:
  port: 8081
girl:
  cupSize: F
  age: 18

//调用配置文件的主配置文件内容
spring:
  profiles:
    active: prod

(2)创建配置文件属性类

package com.echodemo.girl;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

//获取前缀是girl的配置,注入配置需要加Component注解
@Component
@ConfigurationProperties(prefix = "girl")
public class GirlProperties {

    private String cupSize;

    private Integer age;

    public String getCupSize() {
        return cupSize;
    }

    public void setCupSize(String cupSize) {
        this.cupSize = cupSize;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

(3)HelloController文件内容

package com.echodemo.girl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

/*    //通过注解的方式获取配置文件值(Value注解太low了)
    @Value("${server.cupSize}")
    private String cupSize;

    @Value("${server.age}")
    private Integer age;*/


    //通过创建配置文件属性类来获取配置文件中的值
    @Autowired
    private GirlProperties girlProperties;

    @RequestMapping(value = "/hello",method = RequestMethod.GET)
    public String say(){
        return girlProperties.getCupSize();
    }
}
🐶 您的支持将鼓励我继续创作 🐶
-------------本文结束感谢您的阅读-------------