Spring Boot 学习之环境搭建

来源:互联网 发布:网络语不二臣 什么意思 编辑:程序博客网 时间:2024/05/17 08:08

引言:

SpringBoot 、可以快速的搭建 Spring 框架环境,官方推荐使用配置类的方式去配置或自定义配置,所以需要学习的人有一定的Spring框架使用基础,注解使用的基础

搭建:

IDE:IntelliJ IDEA

管理工具:Maven、Git/GitHub  具体使用请参考其他文章

一、pom.xml 文件

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  <modelVersion>4.0.0</modelVersion>  <groupId>spring</groupId>  <artifactId>springboot</artifactId>  <packaging>war</packaging>  <version>1.0-SNAPSHOT</version>  <!-- 默认继承自 Spring Boot 官方的指定版本 -->  <parent>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-parent</artifactId>    <version>1.5.2.RELEASE</version>  </parent>  <name>springboot Maven Webapp</name>  <url>http://maven.apache.org</url>  <dependencies>    <dependency>      <groupId>junit</groupId>      <artifactId>junit</artifactId>      <version>4.12</version>      <scope>test</scope>    </dependency>    <!-- Add typical dependencies for a web application. spring-boot-starter-web -->    <dependency>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot-starter-web</artifactId>    </dependency>    <!-- Add test dependencies for this wen application. spring-boot-starter-test -->    <dependency>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot-starter-test</artifactId>    </dependency>    <!-- additional json style message converter. -->    <dependency>      <groupId>com.alibaba</groupId>      <artifactId>fastjson</artifactId>      <version>1.2.28</version>    </dependency>  </dependencies>  <!-- Package as an executable jar -->  <build>    <finalName>springboot</finalName>    <plugins>      <plugin>        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-maven-plugin -->          <groupId>org.springframework.boot</groupId>          <artifactId>spring-boot-maven-plugin</artifactId>      </plugin>    </plugins>  </build></project>

二、目录结构

三、启动文件:Application  (自定义类名)

package com.springboot.boot;import com.alibaba.fastjson.serializer.SerializerFeature;import com.alibaba.fastjson.support.config.FastJsonConfig;import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter4;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.http.MediaType;import org.springframework.http.converter.HttpMessageConverter;import org.springframework.http.converter.StringHttpMessageConverter;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;import java.nio.charset.Charset;import java.util.ArrayList;import java.util.List;/** * This is where the spring boot start. * The references of the annotation '@SpringBootApplication' in Spring Official Docs. * "Many Spring Boot developers always have their main class annotated with @Configuration, @EnableAutoConfiguration and @ComponentScan. *  Since these annotations are so frequently used together (especially if you follow the best practices above), Spring Boot provides a convenient @SpringBootApplication alternative. *  The @SpringBootApplication annotation is equivalent to using @Configuration, @EnableAutoConfiguration and @ComponentScan with their default attributes * Created by Vincent on 2017/3/13. * @author Vincent * @version 1.0.0 * Description: Spring Boot Starter */@SpringBootApplicationpublic class Application extends WebMvcConfigurerAdapter{    /**     * this is a method of the WebMvcConfigurerAdapter.class     * we can override the default value/achievements of spring boot     * and customize our own HttpMessageConverters.     * @param converters     */    @Override    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {        /*            using the StringHttpMessageConverter to handle with simple String message.        */        StringHttpMessageConverter stringConverter= new StringHttpMessageConverter();        stringConverter.setDefaultCharset(Charset.forName("UTF-8"));        converters.add(stringConverter);        /*            using the FastJsonHttpMessageConverter to handle these below.            1. text/html;charset=UTF-8                              a page(htm/html/jsp etc.)            2. application/json;charset=utf-8                       json data type response            3. text/plain;charset=UTF-8                             a text or string etc.            4. application/x-www-form-urlencoded;charset=utf-8      standard encoding type. convert form data to a key-value.            ...        */        FastJsonHttpMessageConverter4 fastJsonConverter = new FastJsonHttpMessageConverter4();        FastJsonConfig fastJsonConfig = new FastJsonConfig();        fastJsonConfig.setCharset(Charset.forName("UTF-8"));        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);        fastJsonConverter.setFastJsonConfig(fastJsonConfig);        List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();        MediaType text_plain = new MediaType(MediaType.TEXT_PLAIN, Charset.forName("UTF-8"));        MediaType text_html = new MediaType(MediaType.TEXT_HTML, Charset.forName("UTF-8"));        MediaType x_www_form_urlencoded_utf8 = new MediaType(MediaType.APPLICATION_FORM_URLENCODED, Charset.forName("UTF-8"));        supportedMediaTypes.add(text_html);        supportedMediaTypes.add(text_plain);        supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);        supportedMediaTypes.add(x_www_form_urlencoded_utf8);        fastJsonConverter.setSupportedMediaTypes(supportedMediaTypes);        converters.add(fastJsonConverter);        super.configureMessageConverters(converters);    }    public static void main(String[] args) {        SpringApplication.run(Application.class, args);    }}

四、application.properties    配置文件

server.port=9000server.servlet-path=/springbootspring.mvc.servlet.load-on-startup=1

五、HelloWorldController

package com.springboot.boot;import com.springboot.model.Users;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;/** * Created by Vincent on 2017/3/13. * Version 1.0.0 * Description a simple controller demo using spring boot annotations. */@RestController@RequestMapping("/test")public class HelloWorldController {    private static final Logger logger = LoggerFactory.getLogger(HelloWorldController.class);    @RequestMapping("/hello")    public Object hello(){        logger.info("Hello World! Which means you have build the web application with spring boot 'AutoConfiguration' mode successfully.");        /*         step 1 : test the request, the response value should be         "Hello World! Which means you have build the web application with spring boot 'AutoConfiguration' mode successfully"         with quotes          *///        return "Hello World! Which means you have build the web application with spring boot 'AutoConfiguration' mode successfully. 你好";        /*          step 2 test fastJson json serialization/formatter           */        Users user = new Users();        user.setUid(1);        user.setUname("Vincent Wang 汉字测试");        return user;                                        //  response on thte page should be {"uid":1,"uname":"Vincent Wang"}        /*          step 3 test simple String response          1. make the application.class extends the WebMvcConfigurerAdapter          2. override the method 'configureMessageConverters' to reset the 'List<HttpMessageConverter<?>> converters'.          3. disable step 2, enable step 1, sending a request on the browse or somewhere, see what happened.           */    }}

六、Users

package com.springboot.model;import com.alibaba.fastjson.annotation.JSONField;/** * Created by Vincent on 2017/3/14. */public class Users {    public int uid;    /**     * By adding this annotation '@JSONField(serialize = false)', we can figure out whether the configuation of fastJsonMessageConverter is effective or not.     * if it worked, the result we got at the page should not contain the uname field     * before add: { "uid":1, "uname":"Vincent Wang" }, after add: { "uid":1 }     */    public String uname;    public int getUid() {        return uid;    }    public void setUid(int uid) {        this.uid = uid;    }    public String getUname() {        return uname;    }    public void setUname(String uname) {        this.uname = uname == null ? "" : uname;    }    @Override    public String toString() {        return "Users{" +                "uid=" + uid +                ", uname='" + uname + '\'' +                '}';    }}

七、运行Application.class

  .   ____          _            __ _ _ /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/  ___)| |_)| | | | | || (_| |  ) ) ) )  '  |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot ::        (v1.5.2.RELEASE)2017-03-15 15:09:17.356  INFO 3004 --- [           main] com.springboot.boot.Application          : Starting Application on Vincent-PC with PID 3004 (started by Vincent in E:\Intellij Workspace\springboot)2017-03-15 15:09:17.359  INFO 3004 --- [           main] com.springboot.boot.Application          : No active profile set, falling back to default profiles: default2017-03-15 15:09:17.498  INFO 3004 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@24cd504e: startup date [Wed Mar 15 15:09:17 CST 2017]; root of context hierarchy2017-03-15 15:09:18.667  INFO 3004 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 9000 (http)2017-03-15 15:09:18.675  INFO 3004 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat2017-03-15 15:09:18.676  INFO 3004 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.112017-03-15 15:09:18.757  INFO 3004 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext2017-03-15 15:09:18.757  INFO 3004 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1264 ms2017-03-15 15:09:18.873  INFO 3004 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/springboot/*]2017-03-15 15:09:18.877  INFO 3004 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]2017-03-15 15:09:18.877  INFO 3004 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]2017-03-15 15:09:18.877  INFO 3004 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]2017-03-15 15:09:18.877  INFO 3004 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]init server port:90002017-03-15 15:09:19.177  INFO 3004 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@24cd504e: startup date [Wed Mar 15 15:09:17 CST 2017]; root of context hierarchy2017-03-15 15:09:19.227  INFO 3004 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/test/hello]}" onto public java.lang.Object com.springboot.boot.HelloWorldController.hello()2017-03-15 15:09:19.230  INFO 3004 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)2017-03-15 15:09:19.230  INFO 3004 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)2017-03-15 15:09:19.257  INFO 3004 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]2017-03-15 15:09:19.257  INFO 3004 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]2017-03-15 15:09:19.292  INFO 3004 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]2017-03-15 15:09:19.445  INFO 3004 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup2017-03-15 15:09:19.486  INFO 3004 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet 'dispatcherServlet'2017-03-15 15:09:19.486  INFO 3004 --- [           main] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started2017-03-15 15:09:19.498  INFO 3004 --- [           main] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 12 ms2017-03-15 15:09:19.498  INFO 3004 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 9000 (http)2017-03-15 15:09:19.501  INFO 3004 --- [           main] com.springboot.boot.Application          : Started Application in 2.504 seconds (JVM running for 2.776)

八、访问   http://localhost:9000/springboot/test/hello 得到如下结果:


未完待续...

0 1
原创粉丝点击