SpringBoot简单入门案例HelloWorld

Spring框架入门案例:(HelloWorld)

         1:创建一个MavenProject

         2:在Pom.xml中添加依赖关系(spring-boot-starter-web)

<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>

Spring Boot提供了一些“父级”,会让我们在添加jar使变得很方便。这spring-boot-starter-parent是一个特殊的启父级,提供一些有用的Maven默认值。它还提供了一个 dependency-management 部分,因此我们可以省略<version>标签,他会默认从父级集成下来。

 由于我们正在开发一个Web应用程序,我们将添加一个spring-boot-starter-web这样的jar包,它会依赖于SpringMVC等各种jar包 还有就是Tomcat Web服务器,所以我们只导入这一个即可。

     3:创建SpringBoot的启动类:WebApplication .java

 

importorg.springframework.boot.*;

importorg.springframework.boot.autoconfigure.*;

importorg.springframework.stereotype.*;

importorg.springframework.web.bind.annotation.*;

 @RestController

@EnableAutoConfiguration

 public class WebApplication {

 @RequestMapping("/")

    String home(){

        return  "Hello World!";

    }}

     public  static  voidmain(String []args)throws Exception {

        SpringApplication.run(WebApplication.class,args);

    }}

}}


Spring的简单的入门程序到这已经完成了,那让我们一起来看一下结果吧。

打开浏览器访问:http://ip:port/

会出现Hello World.

下面对上面的几个注解进行一些解释吧,

    1:@RestController:相当于@ResponseBody+@Controller合在一起使用

    举个栗子:

1)如果只是使用@RestController注解Controller,则Controller中的方法无法返回jsp页面,配置的视图解析器InternalResourceViewResolver不起作用,返回的内容就是Return里的内容。

例如:本来应该到success.jsp页面的,则其显示success.

2)如果需要返回到指定页面,则需要用 @Controller配合视图解析器InternalResourceViewResolver才行。
3)如果需要返回JSON,XML或自定义mediaType内容到页面,则需要在对应的方法上加上@ResponseBody注解。

    2:@EnableAutoConfiguration:用于自动配置,SpringBoot会根据你的pom.xml配置(实际上根据具体的依赖)来判断这是一个什么应用,并创建相应的环境


SpringApplication类:用于从Main方法,启动Spring应用的类。默认他会执行以下步骤:

         1:创建一个合适的ApplicationContext实例

        2: 注册一个CommandLinePropertySource,以便将命令行参数作为SpringProperties

         3:刷新applicationcontext,加载所有的单例Beans

         4:激活所有CommandLineRunnerbeans.

 完.


猜你喜欢

转载自blog.csdn.net/huhao_csdn/article/details/80406783
今日推荐