SpringBoot實戰:SpringBoot之Hello world

這裏以最新的2.2.0.RELEASE版本爲例子,別問我爲啥,由於它是目前爲止最新的一個版本。java

建立maven工程,引入依賴git

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.wusy.demo</groupId>
    <artifactId>spring-boot-wusy-demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!-- 繼承SpringBoot父包 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
        <relativePath></relativePath>
    </parent>

    <dependencies>
        <!-- spring boot web支持:mvc,aop... -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

    </dependencies>
    
</project>

在resource下建立application.properties或者application.yml,SpringBoot會自動加載這個兩個配置文件。web

#編碼設置
server.tomcat.uri-encoding=UTF-8
spring.http.encoding.charset=UTF-8
spring.http.encoding.force=true
spring.http.encoding.enabled=true
spring.messages.encoding=UTF-8

# tomcat 配置
server.tomcat.accept-count=1000
server.tomcat.max-threads=500
# session超時時間,單位是秒
server.servlet.session.timeout=1800

#當前應用http端口
server.port=8787
#訪問地址,該配置能夠不配置,則直接經過ip+port訪問
#server.servlet.context-path=/demo

建立SpringBoot啓動類spring

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author wusy
 * Company: xxxxxx科技有限公司
 * Createtime : 2020/2/24 21:42
 * Description : SpringBoot應用啓動器
 */
@SpringBootApplication
public class Application {

    private static Logger logger = LoggerFactory.getLogger(Application.class);

    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(Application.class);
        application.run(args);
        logger.info("啓動成功");
    }
}

建立Controllerapache

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author wusy
 * Company: xxxxxx科技有限公司
 * Createtime : 2020/2/24 21:54
 * Description :
 */
@RestController
@RequestMapping("/api/demo")
public class HelloWorldController {

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String hello() {
        return "hello world";
    }
}

運行Application類api

打開瀏覽器,在地址欄輸入http://127.0.0.1:8787/api/demo/hello瀏覽器

至此,SpringBoot簡單的Hello world例子演示完畢。tomcat

項目碼雲地址:https://gitee.com/wusycode/spring-boot-wusy-demo.gitsession

相關文章
相關標籤/搜索