Springboot学习笔记

Springboot学习笔记

1.基本配置

1.1springboot的入口类和@SpringBootApplication

POM文件配置


    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>1.5.10.RELEASEversion>
    parent>

    <dependencies>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
    dependencies>

    <build>
        <defaultGoal>installdefaultGoal>
        <plugins>
            
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-compiler-pluginartifactId>
                <version>3.7.0version>
                <configuration>
                    <source>1.8source>
                    <target>1.8target>
                configuration>
            plugin>
            
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-resources-pluginartifactId>
                <version>3.0.2version>
                <configuration>
                    <encoding>UTF-8encoding>
                configuration>
            plugin>
            
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>

启动程序

@SpringBootApplication
public class Application {

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

@SpringBootApplication是SpringBoot的核心注解,是一个组合注解,源码如下

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
        @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
        @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {

    @AliasFor(annotation = EnableAutoConfiguration.class, attribute = "exclude")
    Class[] exclude() default {};

    @AliasFor(annotation = EnableAutoConfiguration.class, attribute = "excludeName")
    String[] excludeName() default {};

    @AliasFor(annotation = ComponentScan.class, attribute = "basePackages")
    String[] scanBasePackages() default {};

    @AliasFor(annotation = ComponentScan.class, attribute = "basePackageClasses")
    Class[] scanBasePackageClasses() default {};
}

1.2 关闭特定的自动配置

关闭特定的自动配置应该使用@SpringBootApplication注解的exclude参数

例:

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})

1.3 定制Banner

在springboot启动的时候会有一个默认的启动图案

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::       (v1.5.10.RELEASE)

在src/main/resources下新建一个banner.txt,通过http://patorjk.com/software/taag网站生成字符,如敲入simba1949,将网站生成的字符复制在banner.txt中,即可定制

Springboot学习笔记_第1张图片

1.4 创建一个可执行的jar

添加打包插件


<plugin>
  <groupId>org.springframework.bootgroupId>
  <artifactId>spring-boot-maven-pluginartifactId>
plugin>

命令运行:mvn package

会得到如下jar包

[INFO] Building jar: D:\Learn\IntelliJ IDEA\Workspace\springboot\springboot01\target\springboot01-1.0-SNAPSHOT.jar

在命令窗口输入下面命令即可运行:

java -jar springboot01-1.0-SNAPSHOT.jar

1.5 SpringBoot的配置文件

springboot使用一个全局的配置文件application.properties或者application.yml,放置在src/main/resources目录下或者类路径/config下

读取properties文件时,需要引入依赖包

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-configuration-processorartifactId>
    <optional>trueoptional>
dependency>

在application.properties中添加如下数据

#配置对应的属性
user.username:simba1949
user.age:hi,${user.username}!!!

@ConfigurationProperties注解读取properties配置文件,prefix=”user”

@Service
@ConfigurationProperties(prefix = "user")
public class UserServiceImpl implements UserService {

    private String username;
    private String say;

    @Override
    public void testProperties(){
        System.out.println(username);
        System.out.println("*******");
        System.out.println(say);
    }
    //需要属性的settter方法
    public void setUsername(String username) {
        this.username = username;
    }
    public void setSay(String say) {
        this.say = say;
    }
}

1.6 属性配置校验

@NotNull
private Integer age;

运行时会报错

Springboot学习笔记_第2张图片

1.7 使用xml配置

@ImportResource({"classpath:ApplicationContext-tran.xml","classpath:ApplicationContext-dao.xml"})

2.日志配置

在application.properties中配置日志系统

#日志配置
#日志级别
logging.level.root=DEBUG
logging.level.org.springframework.web=DEBUG
logging.level.org.hibernate=DEBUG
#输出日志名字
#logging.file=springboot001.log
#日志输出路径
logging.path=D:/logs

3.Profile配置

Profile是Spring用来针对不同的环境进行不同的配置提供支持的,全局Profile配置实用application-{profile}.properties。

通过在application.properties中设置spring.profiles.active=dev指定活动的Profile。

测试:生产环境端口为80,开发环境端口为8888

生产环境(application-prod.properties)配置如下:

server.port=80

开发环境(application-dev.properties)配置如下:

server.port=8888

application.properties配置:

spring.profiles.active=dev

运行如图

Springboot学习笔记_第3张图片

4.SpringBoot运行原理

5.http的编码配置

SpringBoot内置的自动配置功能:http的编码配置

在常规项目中配置http编码的时候在web.xml里配置一个filter

<filter>
    <filter-name>encodingfilter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    <init-param>
        <param-name>encodingparam-name>
        <param-value>UTF-8param-value>
    init-param>
    <init-param>
        <param-name>forceEncodingparam-name>
        <param-value>trueparam-value>
    init-param>
filter>
<filter-mapping>
    <filter-name>encodingfilter-name>
    <url-pattern>/*url-pattern>
filter-mapping>

自动配置要满足俩个条件

  1. 能配置CharacterEncodingFilter这个Bean
  2. 能配置encoding和forceEncoding这俩个参数

默认编码方式为UTF-8,若修改可使用spring.http.encoding.charset=编码;

设置forceEncoding,默认为true,若修改可使用spring.http.encoding.force=false

6.SSL配置

将生成的.keystore文件复制到项目的根目录下,然后再application.properties中配饰SSL

server.ssl.key-store=mykey.keystore
server.ssl.key-password=123456
server.ssl.key-store-type=JKS
server.ssl.key-alias=tomcat

这里写图片描述

目录结构

Springboot学习笔记_第4张图片

7.SpringBoot的开发

7.1Tomcat配置

springboot默认内嵌Tomcat为servlet容器

配置servlet容器

 #配置程序端口,默认为8080
server.port=
#用户会话session过期时间,以秒为单位
server.session.timeout=
#配置访问路径,默认为/
server.context-path=

配置tomcat

#配置tomcat编码,默认为utf-8
server.tomcat.uri-encoding=

7.2Favicon配置

springboot默认开启,关闭favicon在application.properties中配置即可

spring.mvc.favicon.enabled=false

定制Favicon

需要spring.mvc.favicon.enabled开启,不配置默认开启也可,将favicon.ico(文件名不能变动过)放置在src/main/resources/static下即可,运行效果

Springboot学习笔记_第5张图片

目录结构

Springboot学习笔记_第6张图片

7.3集成springmvc

Json Rest实现

在springboot应用中,任何spring@RestController默认渲染为JSON响应

例如:

@GetMapping(value = "/list",produces = "application/json")
    @ResponseBody
    public List list(){
        List users = new ArrayList();
        users.add(new User("李白","诗仙"));
        users.add(new User("杜甫","诗圣"));
        users.add(new User("王维","诗佛"));
        users.add(new User("白居易","诗魔"));
        users.add(new User("李贺","诗鬼"));
        users.add(new User("苏轼","诗神"));
        return  users;
    }

这里写图片描述

XML Rest实现

如果classpath下存在Jackson XML扩展(jackson-dataformat-xml) , 它会被用来渲染XML响应, 示例和JSON的非常相似。想要使用它, 只需为你的项目添加以下的依赖


<dependency>
  <groupId>com.fasterxml.jackson.dataformatgroupId>
  <artifactId>jackson-dataformat-xmlartifactId>
dependency>

例如:

@GetMapping(value = "/xml",produces = "application/xml")
    @ResponseBody
    public List xml(){
        List users = new ArrayList();
        users.add(new User("李 白","诗仙"));
        users.add(new User("杜 甫","诗圣"));
        users.add(new User("王 维","诗佛"));
        users.add(new User("白居易","诗魔"));
        users.add(new User("李 贺","诗鬼"));
        users.add(new User("苏 轼","诗神"));
        return  users;
    }

Springboot学习笔记_第7张图片

SpringMVC视图解析器配置

由于springboot已经不推荐使用jsp了,如果想使用jsp,需要手动引入相关依赖包。


<dependency>
    <groupId>org.apache.tomcat.embedgroupId>
    <artifactId>tomcat-embed-jasperartifactId>
    
dependency>

<dependency>
    <groupId>javax.servletgroupId>
    <artifactId>javax.servlet-apiartifactId>
    
dependency>

<dependency>
    <groupId>javax.servletgroupId>
    <artifactId>jstlartifactId>
dependency>

在application.properties配置视图解析器

#视图解析器
spring.mvc.view.prefix=/WEB-INF/view/
spring.mvc.view.suffix=.jsp

7.4集成MyBatis

pom文件添加依赖

<dependency>
    <groupId>org.mybatis.spring.bootgroupId>
    <artifactId>mybatis-spring-boot-starterartifactId>
    <version>1.3.1version>
dependency>
<dependency>
    <groupId>mysqlgroupId>
    <artifactId>mysql-connector-javaartifactId>
    <version>6.0.6version>
    <scope>runtimescope>
dependency>

mybatis在application.properties配置

#配置数据源
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=19491001
#表示打印出sql语句
logging.level.com.shyroke.mapper=debug

#mybatis配置
mybatis.mapper-locations=classpath*:top/simba1949/mapper/*Mapper.xml
mybatis.type-aliases-package=top.simba1949.entity

还需要在Application配置@MapperScan(basePackages = “top.simba1949.mapper”)

@SpringBootApplication
//@mapperscan 指定被扫描的mapper所在的包路径
@MapperScan(basePackages = "top.simba1949.mapper")
public class Application {

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

7.5 集成druid连接池

pom文件添加依赖


<dependency>
  <groupId>com.alibabagroupId>
  <artifactId>druidartifactId>
  <version>1.0.20version>
dependency>

在application.properties配置

#配置数据源
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=19491001
#表示打印出sql语句
logging.level.com.shyroke.mapper=debug

# 下面为连接池的补充设置,应用到上面所有数据源中
# 初始化大小,最小,最大
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20

7.6 声明式事务配置

7.6.1 基于注解

只需要在参与事务控制的方法上加上@Transactional注解即可。

@Transactional
@Override
public void addUser(User user) {
    int acount = userMapper.addUser(user);
}

7.6.2 基于xml配置文件

引入aop依赖

<dependency>
  <groupId>org.springframework.bootgroupId>
  <artifactId>spring-boot-starter-aopartifactId>
dependency>

xml事务传播特性配置


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">


    
    <aop:config>
        <aop:pointcut expression="execution(* top.simba1949.service.impl.*.*(..))" id="tranpointcut" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="tranpointcut" />
    aop:config>
    
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED" isolation="DEFAULT"
                       rollback-for="java.lang.Exception" />
            <tx:method name="save*" propagation="REQUIRED" isolation="DEFAULT"
                       rollback-for="java.lang.Exception" />
            <tx:method name="insert*" propagation="REQUIRED" isolation="DEFAULT"
                       rollback-for="java.lang.Exception" />
            
            <tx:method name="query*" read-only="true" />
            <tx:method name="select*" read-only="true" />
            <tx:method name="find*" read-only="true" />
        tx:attributes>
    tx:advice>
    
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    bean>
beans>

配置导入

@SpringBootApplication
//@mapperscan 指定被扫描的mapper所在的包路径
@MapperScan(basePackages = "top.simba1949.mapper")
//@ImportResource 导入事务配置
@ImportResource(value = "classpath:spring-aop.xml")
public class Application {

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

7.7 文件上传

配置文件上传属性

#默认支持文件上传.
spring.http.multipart.enabled=true
#支持文件写入磁盘.
spring.http.multipart.file-size-threshold=0
# 最大支持文件大小
spring.http.multipart.max-file-size=1Mb
# 最大支持请求大小
spring.http.multipart.max-request-size=10Mb

java代码

@RestController
@RequestMapping(value = "/upload")
public class UploadController {

    @PostMapping(value = "/image")
    public String image(@RequestParam(value = "userimage")MultipartFile file, HttpSession session) throws  Exception{
        //获取upload目录,不存在就创建
        String realPath = session.getServletContext().getRealPath("upload");
        File path = new File(realPath);
        if(!path.exists()){
            path.mkdirs();
        }
        //上传
        file.transferTo(new File(realPath+"/"+file.getOriginalFilename()));
        return "http://localhost:8080/upload/"+file.getOriginalFilename();
    }
}

7.8 注册拦截器

7.8.1自定义拦截器

public class UserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        System.out.println("preHandle-------------------------------");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle-------------------------------");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("afterCompletion-------------------------------");
    }
}

7.8.2 注册拦截器

@Configuration
public class WebRegister extends WebMvcConfigurerAdapter {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new UserInterceptor()).addPathPatterns("/add");
        super.addInterceptors(registry);
    }
}

7.9 springboot异常处理

@ControllerAdvice

该注解是spring2.3以后新增的一个注解,主要是用来Controller的一些公共的需求的低侵入性增强提供辅助,作用于@RequestMapping标注的方法上。

@ExceptionHandler

该注解是配合@ControllerAdvice一起使用的注解,自定义错误处理器,可自己组装json字符串,并返回到页面。

@ControllerAdvice
public class ErrorHandlerController {

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public String handleGlobalException(Exception e){
        System.out.println("0000000000000000000000------------------00000000000000000000000000"+e.getMessage());
        return "error";
    }
}

你可能感兴趣的:(SpringBoot)