SpringBoot配置详情

来源:互联网 发布:mysql source命令 编辑:程序博客网 时间:2024/05/17 20:01

                                                                                   SpringBoot配置

  目录

    springboot路径结构图

一,pom.xml

二,Application主程序

    1.初始

    2.整合fastjson

    3.自定义拦截器

    4.静态资源处理

    5.mybatis

三,Application.properties文件配置

   1.thymeleaf模版视图解析 

   2.数据库配置


springboot路径结构图:



1.Application为springBoot主程序 注意:文件需在所实现包之上

2.application.properties为配置文件;

3.banner.txt为自定义启动logo;

4.templates文件夹存储html文件;

5.logging.log为日志文件;



一,pom.xml

首先是maven的pom.xml文件配置:

<?xml version="1.0" encoding="UTF-8"?><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>  <packaging>war</packaging>  <name>cai</name>  <groupId>com</groupId>  <artifactId>cai</artifactId>  <version>1.0-SNAPSHOT</version>  
 <!--这个parent必须设置 -->
  <parent>
    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-parent</artifactId>
    <!--这里设置了版本号后,后面springboot相关的起步依赖就不需要设置版本好了 -->
<version>1.5.4.RELEASE</version> </parent> <properties> <java.version>1.8</java.version> </properties> <dependencies>
                        
  <!--==================SpringBootWeb起步依赖=================================-->
                            <!--web支持-->
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
<!--==================SpringBootTomcat起步依赖=================================-->
                            <!--tomcat支持-->
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <!--<scope>provided</scope>--> </dependency>
<!--==================SpringBootMybatis起步依赖=================================-->
                             <!--mybatis支持-->
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.0</version> </dependency>
<!--==================SpringBootDevTools起步依赖=================================-->
                             <!--热部署支持-->
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency>
<!--==================FastJSON=================================-->
                          <!--json支持-->
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.33</version> </dependency>
<!-- <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency>--> 
<!--==================SpringBootLog4j起步依赖=================================-->
                            <!--日志支持-->
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j</artifactId> </dependency>
<!--==================SpringBootThyMeLeaf起步依赖=================================-->
                              <!--mvc支持-->
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
 <!--==================SpringBootFreemarker起步依赖=================================-->
                              <!--mvc支持-->
                   <!--同上,可任选其一也可同时存在不冲突-->
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency>
 <!--==================Mysql链接驱动=================================-->
                           <!--mysql支持-->
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.42</version>
  </dependencies>  <build>    <plugins>      <plugin>        <groupId>org.apache.maven.plugins</groupId>        <artifactId>maven-compiler-plugin</artifactId>        <configuration>          <source>1.8</source>          <target>1.8</target>        </configuration>      </plugin>      <plugin>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-maven-plugin</artifactId>        <configuration>          <fork>true</fork>        </configuration>      </plugin>      <plugin>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-loader</artifactId>        <version>1.5.4.RELEASE</version>      </plugin>    </plugins>  </build></project>

二,Application主程序

Application.java文件配置:

1.初始

@SpringBootApplicationpublic class Application{ public static void main(String[] args) {        SpringApplication.run(Application.class,args);    }}
讲解:
       首先需在所在类之上加入@SpringBootApplication注解标记该类为springboot应用程序;然后写个main方法使用springApplication的run方法,需要两个参数分别是本类的class和main方法的String数组args;

2.整合fastjson

@SpringBootApplicationpublic class Application extends WebMvcConfigurerAdapter{    /**     * @Author CWX     * 添加fastJson     */    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {        super.configureMessageConverters(converters);        FastJsonHttpMessageConverter fastJsonHttpMessageConverter=new FastJsonHttpMessageConverter();        FastJsonConfig fastJsonConfig=new FastJsonConfig();        fastJsonConfig.setSerializerFeatures(                SerializerFeature.PrettyFormat        );
        //解决中文乱码        List<MediaType> mediaTypeList=new ArrayList<>();        mediaTypeList.add(MediaType.APPLICATION_JSON_UTF8);        fastJsonHttpMessageConverter.setSupportedMediaTypes(mediaTypeList);        fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);        converters.add(fastJsonHttpMessageConverter);    }  public static void main(String[] args) {        SpringApplication.run(Application.class,args);    }}


3.自定义拦截器


@SpringBootApplicationpublic class Application extends WebMvcConfigurerAdapter{
    /**     * @Author CWX     * 添加拦截器     */
public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MyInterceptors()).addPathPatterns("/**").excludePathPatterns("**.html,/login"); } public static void main(String[] args) { SpringApplication.run(Application.class,args); }}

MyInterceptors.java文件配置:
 
public class MyInterceptors implements HandlerInterceptor { public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {        String url=httpServletRequest.getRequestURI();        HttpSession httpSession=httpServletRequest.getSession();        User user= (User) httpSession.getAttribute(StaticCode.LOGINSESSION);        System.out.println(url);        boolean result=equalsUrl(url);        if (!Validation.objectNotEmpty(user) && result==false){//没有session且路径            if (url.equals("/index")){                return true;            }            httpServletResponse.sendRedirect("/index");            return false;        }//有session        return true;    }    @Override    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {    }    @Override    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {    }}


4.静态资源处理

@SpringBootApplicationpublic class Application extends WebMvcConfigurerAdapter {    /**     * @Author CWX     * 静态资源处理     */    public void addResourceHandlers(ResourceHandlerRegistry registry) {        registry.addResourceHandler("/static/**")  //影射路径                .addResourceLocations("classpath:/static/");  //本地路径    }    public static void main(String[] args) {        SpringApplication.run(Application.class,args);    }} 

5.mybatis

@MapperScan(basePackages ="#")//#为Mybatis的mapper文件所在包
@SpringBootApplicationpublic class Application  {  public static void main(String[] args) {        SpringApplication.run(Application.class,args);    }}
MybatisMapper示例:
@Componentpublic interface UserMapper {    /**     * 插入用户     */    @Insert("insert into user (user_name,user_pwd) values (#{userName},#{userPwd})")    int insertSelective(User record);    /**     *查询用户     */    @Select("select id,user_name,user_pwd from user where user_name=#{user_name} and user_pwd=#{user_pwd}")    @Results(value = {@Result(property ="id",column = "id"), @Result(property ="userName",column = "user_name"), @Result(property ="userPwd",column = "user_pwd")})    User selectByNameAndPwd(@Param("user_name") String userName,@Param("user_pwd") String userPwd);    @Select("select id,user_name,user_pwd from user where user_name=#{user_name}")    @Results(value = {@Result(property ="id",column = "id"), @Result(property ="userName",column = "user_name"), @Result(property ="userPwd",column = "user_pwd")})    User selectByName(@Param("user_name") String userName);}


三,Application.properties文件配置
1.thymeleaf模版视图解析

application.properties配置文件:

spring.thymeleaf.cache=falsespring.thymeleaf.prefix=classpath:/templates/spring.thymeleaf.suffix=.html

2.数据库配置

application.properties配置文件:

spring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8spring.datasource.username=rootspring.datasource.password=root



--------------------------------------------------------------------------------------------------------end-------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------本文供本人长久记忆,供他人学习参考,以后会持续完善的,现在还没这精力再写下去;------------------------------------------------------------------