美文网首页javaspringcloud
springcloud学习01—第一个基于springboot的

springcloud学习01—第一个基于springboot的

作者: 牛海朋 | 来源:发表于2017-03-22 19:04 被阅读0次

    这篇文章主要介绍怎么使用Spring Boot快速创建一个web项目。

    快速开始

    增加maven配置

        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.5.1.RELEASE</version>
        </parent>
        
        <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>
    
    

    详情: pom.xml

    创建controller

    @RestController
    public class HelloController {
      @RequestMapping
      public String hello() {
        return "hello,world!";
      }
    }
    

    详情: HelloController.java

    创建启动类

    @SpringBootApplication
    public class Application {
      public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
      }
    }
    

    详情: Application.java

    运行

    直接运行main方法,在浏览器打开http://127.0.0.1:8080/即可看到结果

    思考

    1. 开发一个web项目真的只需要这么少的依赖吗?
    当然不是。在pom文件上按下ctrl+alt+shift+u(idea项目)你会发现,我们的web项目其实是Spring Boot帮我们集成了springmvc和tomcat。


    2. Application是如何扫描到我的controller的?
    打开SpringBootApplication注解的源码可以看到它上面有个ComponentScan注解,也就是会扫描Application当前包及其子包下的spring组件
    @ComponentScan(
      excludeFilters = {@Filter(
      type = FilterType.CUSTOM,
      classes = {TypeExcludeFilter.class}
    ), @Filter(
      type = FilterType.CUSTOM,
      classes = {AutoConfigurationExcludeFilter.class}
    )}
    )
    public @interface SpringBootApplication 
    

    这点我们可以通过再写一个启动类Application2.java来验证。
    Application2上不加ComponentScan注解的情况下,运行程序将加载不到任何controller(因为app包下没有),而加上

    @ComponentScan("com.niuhp.springcloud.sample.helloworld")
    

    就可以加载到HelloControllerHelloZhController
    但如果是

    @ComponentScan("com.niuhp.springcloud.sample.helloworld.controller")
    

    则只能加载到HelloController
    3. 如何指定端口?
    我们只需要在java启动程序传入参数或者直接修改main方法参数就可以了,Spring Boot支持各种自定义参数,这里不再重复,以后找机会详细介绍。

    --server.port=自定义端口号
    

    本文代码位置:helloworld

    相关文章

      网友评论

        本文标题:springcloud学习01—第一个基于springboot的

        本文链接:https://www.haomeiwen.com/subject/mcqanttx.html