zoukankan      html  css  js  c++  java
  • springboot之HelloWorld

    简介

    为了简化开发Spring的复杂度,Spring提供了SpringBoot可以快速开发一个应用,这里就简单介绍下SpringBoot如何快速开发一个J2EE应用

    HelloWorld

    首先在gradle配置文件中引入SpringBoot

    compile("org.springframework.boot:spring-boot-starter-web:1.4.0.RELEASE")
    

    刷新项目后他会默认引入Spring的依赖以及内嵌tomcat,配置就这一步,下面就开始开发了

    @SpringBootApplication
    public class App {
        public static void main(String[] args) throws Exception {
            SpringApplication.run(new Object[]{App.class}, args);
        }
    }
    

    以上就配置好了应用可以运行了,这里简单说下加的注解
    @SpringBootApplication=@SpringBootConfiguration+@EnableAutoConfiguration+@ComponentScan
    SpringBootConfiguration是以Configuration类的方式配置Spring相当于spring.xml可以使用@Bean注册一个实例
    EnableAutoConfiguration是告诉SpringBoot自动配置Spring应用
    ComponentScan是让spring扫描注解
    下面就可以开发Controller了,这个和SpringMVC一样,其中RestController是Controller和ResponseBody的合体。

    @RestController
    public class MyController{
        @RequestMapping("/")
        String home() {
        	return "Hello World!";
        }
    }
    

    运行App的main方法,就可以看到应用启动,可以访问localhost:8080了

    热部署

    IDE中的server都支持热部署,只要改了代码就会自动重新发布,这里使用SpringBoot由于是直接运行的main方法,所以没有这个功能。
    不过Spring团队提供了dev-tool可以实现这个功能,使用也很方便,只要引入相应jar就行

    compile 'org.springframework.boot:spring-boot-devtools:1.4.0.RELEASE' 
    

    这样只要有类改动,IDE会自动重编译(需要打开该功能),SpringBoot就会自动重新部署

    总结

    SpringBoot提供了一个很简单的开发流程,大大减少了繁琐的Spring配置,新项目可以尝试使用

    注意

    在运行springboot应用时遇到一个问题

    ** WARNING ** : Your ApplicationContext is unlikely to start due to a @ComponentScan of the default package.
    2016-11-13 21:16:43.923  WARN 8292 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class [App]; nested exception is org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name 'errorPageFilter' for bean class [org.springframework.boot.web.support.ErrorPageFilter] conflicts with existing, non-compatible bean definition of same name and class [org.springframework.boot.context.web.ErrorPageFilter]
    
    

    这个是由于app类建在default包中,一定不要将app类放在默认包中,不然会导致各种奇怪的异常

  • 相关阅读:
    ubuntu播放器
    第一次装ubuntu 没root密码时
    web服务器记录
    socket udp编程步骤
    nfs服务器配置
    带线程函数编译条件
    linux使用一个刚编译驱动方法
    tiny6410_led驱动Makefile
    java-设计模式-外观模式
    java-实现一个简单的java Web容器
  • 原文地址:https://www.cnblogs.com/resentment/p/5954219.html
Copyright © 2011-2022 走看看