从零学springboot——hello world

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mazhen1991/article/details/79520025

使用springboot搭建web项目

  • 新建一个maven项目
  • 导入依赖
<parent>
        <!--  springboot根依赖 -->
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
    </parent>

    <dependencies>
        <!-- springboot web 依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!-- springboot 启动插件 -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <!-- 指定编译版本 -->
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

以上依赖是一个springboot项目最基本的依赖,其中springboot启动插件的作用就是可以直接通过启动main方法来跑web项目。如果是通过maven指令的方式进行启动,则可省略。

  • 编写启动类
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}
  • 编写helloworld的controller
@Controller
public class HelloWorldController {

    @RequestMapping("hello/world")
    @ResponseBody
    public String helloWorld(){
        return "hello world";
    }
}

这里的controller和平时写的没什么区别,只有一点需要注意,在传统的web项目中,我们需要通过配置文件来配置容器扫描包的路径,springboot在默认情况下,会扫描所有和启动类(就是这里的Application)同级的包及子包的所有文件,如果我们需要自定义扫描包,只需要在启动类上添加注解@ComponentScan(basePackages={“”})即可(引号中为配置路径,多个用逗号分隔)。

  • 启动项目
    如果在导入pom文件的时候,我们添加了启动插件,那么我们可以直接运行main方法,如果没有配置,那么我们需要使用maven指令启动。
  • 使用浏览器访问http://localhost:8080/hello/world

至此,一个最简单的springboot项目就已经搭建完成。

猜你喜欢

转载自blog.csdn.net/mazhen1991/article/details/79520025
今日推荐