1.学习Spring Boot 先找个例子跑跑Hello World

来源:互联网 发布:阿里云域名咋续费 编辑:程序博客网 时间:2024/05/22 04:31

公司项目要用到Spring Boot 从来没用过也不甚了解,先网上四处荡荡,学习东西都是从熟悉的hello world开始,找了一个博客跟着学习。

         先用eclipse 创建了一个Maven项目 pom.xml如下


<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>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.2.5.RELEASE</version>
  </parent>
  <groupId>com.tianmaying</groupId>
  <artifactId>spring-web-demo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>spring-web-demo</name>
  <description>Demo project for Spring WebMvc</description>
  
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
  </properties>


  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
  </dependencies>


  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
  
  
</project>

要先pom.xml运行下载要用到的jar包,然后创建一个测试类


package test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@SpringBootApplication
@RestController
public class Application extends SpringBootServletInitializer implements EmbeddedServletContainerCustomizer{
   @RequestMapping("/")
   public String greeting() {
       return "Hello World! I'm Spring Boot";
   }


   public static void main(String[] args) {
       SpringApplication.run(Application.class, args);
   }
   
   //修改端口
   @Override  
   public void customize(ConfigurableEmbeddedServletContainer container) {  
       container.setPort(8088);  
   }  
}

此处有两个坑一个是必须要有个包(正常项目都是有包结构)不然启动报错,还有就是端口被占用也启动不了,可以修改端口



原创粉丝点击