SpringBoot简单入门

摘要: 原创出处 http://peijie2016.gitee.io 欢迎转载,保留摘要,谢谢!

今天学学springboot,springboot是spring4新出的,目的在于减少配置,加快开发速度,springboot中内嵌了tomcat等。

SpringBoot简单入门_第1张图片
著名的Hello World

来看一个简单的hello world 的小demo。

新建一个maven项目

pom.xml


  4.0.0
  com.lpj
  springboot
  0.0.1-SNAPSHOT
  
  
  
    org.springframework.boot
    spring-boot-starter-parent
    1.3.5.RELEASE
  
  
  
    
    
        org.springframework.boot
        spring-boot-starter-web
    
  
  

我用的是目前比较新的版本,要求jdk1.8

下面我们来输出hello world

新建一个DemoController:

package controller;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author lpj
 * @date 2016年6月10日
 */
@Controller
@EnableAutoConfiguration
public class DemoController {
    @RequestMapping("/")
    @ResponseBody
    String home() {
        return "Hello World!";
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(DemoController.class, args);
    }
}

@EnableAutoConfiguration是开启默认配置参数,就是之前我们pom中spring-boot-starter-parent自带的,tomcat也内嵌了,
所以直接run as Java Application,就ok了。如图


SpringBoot简单入门_第2张图片

然后打开浏览器,输入localhost:8080,回车,就看到结果了

PS:

  • 在resource目录下,我们可以添加一个叫 banner.txt的文件,这样当项目启动的时候,会自动加载这个文件,在控制台输出banner.txt文件中的内容。当然,如果不想看到banner,也可以关闭,方法如下:
public static void main(String[] args) {  
//        SpringApplication.run(DemoController.class, args);  
        SpringApplication application = new SpringApplication(DemoController.class);  
        application.setShowBanner(false);  
        application.run(args);  
    }

或者使用链式语法:

public static void main(String[] args) {  
        // SpringApplication.run(DemoController.class, args);  
        // SpringApplication application = new SpringApplication(DemoController.class);  
        // application.setShowBanner(false);  
        // application.run(args);  
        new SpringApplicationBuilder().showBanner(false).sources(DemoController.class).run(args);  
    }
  • 有一点需要注意,如果run方法和controller分开放,项目入口文件【SpringApplication.run方法所在的那个类】所在的包名,必须要是controller,service,entity等等的包名的上级目录,否则会导致项目启动后无法正确显示显示页面。因为SpringApplication.run()启动时,会扫面同目录以及子目录下的@Controller@Service@Repository@Componet等注解标识的类,如果不在目录不是父子关系,会识别不到,导致问题出现。

你可能感兴趣的:(SpringBoot简单入门)