SpringBoot2-基础

1.入门

  1.1 引入依赖


    org.springframework.boot
    spring-boot-starter-parent
    2.3.4.RELEASE



   
       org.springframework.boot
       spring-boot-starter-web
  

  1.2 创建主程序

/**
 * 主程序类
 * @SpringBootApplication:这是一个SpringBoot应用
 */
@SpringBootApplication
public class MainApplication {

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

  1.3 编写业务

@RestController
public class HelloController {


    @RequestMapping("/hello")
    public String handle01(){
        return "Hello, Spring Boot 2!";
    }


}

  1.4 测试

        直接运行main方法

  1.4 简化配置

        application.properties

server.port=8888

  1.5 简化部署


  
    
      org.springframework.boot
      spring-boot-maven-plugin
    
  

  把项目打成jar包,然后执行 java -jar xxxx.jar

2.了解自动配置原理

  2.1 依赖管理

    2.1.1 父项目做依赖管理


        org.springframework.boot
        spring-boot-starter-parent
        2.3.4.RELEASE

    2.1.2 开发导入starter场景启动器


  org.springframework.boot
  spring-boot-starter
  2.3.4.RELEASE
  compile

    2.1.3 修改默认版本号


        5.1.43

  2.2 自动配置

        1. 自动配好Tomcat

        2. 自动配好SpringMVC

        3. 自动配好Web常见功能

        4. 默认的包结构

  • 主程序所在包及其下面的所有子包里面的组件都会被默认扫描进来
  • 想要改变扫描路径,@SpringBootApplication(scanBasePackages="com.xxx")或者@ComponentScan 指定扫描路径

@SpringBootApplication
等同于
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan("com.atguigu.boot")

        5. 按需加载所有自动配置项

        SpringBoot所有的自动配置功能都在 spring-boot-autoconfigure 包里面

  2.3 容器功能

        1. @Configuration

  • 配置类里面使用@Bean标注在方法上给容器注册组件,默认也是单实例的
  • Full模式与Lite模式

        2. @Import

@Import({User.class, DBHelper.class})
@Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
public class MyConfig {
}

        @Import 高级用法:www.bilibili.com/video/BV1gW411W7wy?p=8

        3. @Conditional

          1) 条件装配:满足Conditional指定的条件,则进行组件注入

          2) 如下

@Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
//@ConditionalOnBean(name = "tom")
@ConditionalOnMissingBean(name = "tom")
public class MyConfig {
}

        3) 继承类

ConditionalOnExpression (org.springframework.boot.autoconfigure.condition)
ConditionalOnEnabledResourceChain (org.springframework.boot.autoconfigure.web)
ConditionalOnMissingClass (org.springframework.boot.autoconfigure.condition)
ConditionalOnCloudPlatform (org.springframework.boot.autoconfigure.condition)
ConditionalOnWarDeployment (org.springframework.boot.autoconfigure.condition)
ConditionalOnProperty (org.springframework.boot.autoconfigure.condition)
ConditionalOnBean (org.springframework.boot.autoconfigure.condition)
Profile (org.springframework.context.annotation)
ConditionalOnRepositoryType (org.springframework.boot.autoconfigure.data)
ConditionalOnResource (org.springframework.boot.autoconfigure.condition)
ConditionalOnClass (org.springframework.boot.autoconfigure.condition)
ConditionalOnMissingBean (org.springframework.boot.autoconfigure.condition)
ConditionalOnJava (org.springframework.boot.autoconfigure.condition)
ConditionalOnSingleCandidate (org.springframework.boot.autoconfigure.condition)
ConditionalOnJndi (org.springframework.boot.autoconfigure.condition)
ConditionalOnWebApplication (org.springframework.boot.autoconfigure.condition)
ConditionalOnNotWebApplication (org.springframework.boot.autoconfigure.condition)

  2.4 原生配置文件引入

    1. @ImportResource 配置文件中定义的 bean 对象加载到Spring容器中

======================beans.xml=========================

       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

   
       
       
   

   
       
   

代码

@ImportResource("classpath:beans.xml")
public class MyConfig {}

======================测试=================
boolean haha = run.containsBean("haha");
boolean hehe = run.containsBean("hehe");
System.out.println("haha:"+haha);//true
System.out.println("hehe:"+hehe);//true

    2. 获取到配置文件数据

       1) application.properties 文件

server.port=8888
mycar.brand = "wwww333"
mycar.price = 1

       2) 方式1 @ConfigurationProperties + @Component

@Component
@ConfigurationProperties(prefix = "mycar")
public class Car {

    private String brand;
    private Integer price;

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public Integer getPrice() {
        return price;
    }

    public void setPrice(Integer price) {
        this.price = price;
    }
}

       3) 方式2 @ConfigurationProperties + @EnableConfigurationProperties

@EnableConfigurationProperties(Car.class)
public Class MyConfig{}

  2.5 自动配置原理入门

  2.6 开发小技巧

    1. Lombok 

        1) 简化JavaBean开发

        2) 依赖


  org.projectlombok
  lombok

        3) 简化JavaBean开发

@NoArgsConstructor
//@AllArgsConstructor
@Data
public class User {

    private String name;
    private Integer age; 
}
#@Data相当于@Getter @Setter @RequiredArgsConstructor @ToString @EqualsAndHashCode这5个注解的合集

        4) 简化日志开发

@Slf4j
@RestController
public class HelloController {
    @RequestMapping("/hello")
    public String handle01(@RequestParam("name") String name){
        
        log.info("请求进来了....");
        
        return "Hello, Spring Boot 2!"+"你好:"+name;
    }
}

    2. dev-tools

        项目或者页面修改以后:Ctrl+F9


   org.springframework.boot
   spring-boot-devtools
   true

    3. Spring Initailizr

        项目初始化向导

3.配置文件

  3.1 文件类型

    1.properties

    2.yaml

        1) 非常适合用来做以数据为中心的配置文件

# yaml表示以上对象
person:
  userName: zhangsan
  boss: false
  birth: 2019/12/12 20:12:33
  age: 18
  pet: 
    name: tomcat
    weight: 23.4
  interests: [篮球,游泳]
  animal: 
    - jerry
    - mario
  score:
    english: 
      first: 30
      second: 40
      third: 50
    math: [131,140,148]
    chinese: {first: 128,second: 136}
  salarys: [3999,4999.98,5999.99]
  allPets:
    sick:
      - {name: tom}
      - {name: jerry,weight: 47}
    health: [{name: mario,weight: 47}]

  3.2 配置提示


        
            
                org.springframework.boot
                spring-boot-maven-plugin
                
                    
                        
                            org.springframework.boot
                            spring-boot-configuration-processor
                        
                    
                
            
        
    

4.Web开发

  1 SpringMVC自动配置概览

  2 简单功能分析

      2.1.静态资源访问

        1) 只要静态资源放在类路径下: called /static (or /public or /resources or /META-INF/resources

        2) 改变默认的静态资源路径

spring:
  mvc:
    static-path-pattern: /res/**

  resources:
    static-locations: [classpath:/haha/]

        3) 静态资源访问前缀

spring:
  mvc:
    static-path-pattern: /res/**

        4) webjar

        自动映射 /webjars/**


    org.webjars
    jquery
    3.5.1

加上上面的依赖,然后访问下面的地址,会自动映射

#访问地址:http://localhost:8080/webjars/jquery/3.5.1/jquery.js 后面地址要按照依赖里面的包路径

      2.2 欢迎页支持

        1)  静态资源路径下index.html

        2)  但是不可以配置静态资源的访问前缀。否则导致 index.html不能被默认访问

spring:
#  mvc:
#    static-path-pattern: /res/**   这个会导致welcome page功能失效

  resources:
    static-locations: [classpath:/haha/]

      2.3 自定义 Favicon

        1) favicon.ico 放在静态资源目录下即可

      2.4 静态资源配置原理

  3 请求参数处理

    3.1.请求映射

        1.1. rest使用与原理 

        核心Filter;HiddenHttpMethodFilter

spring:
  mvc:
    hidden-method:
      filter:
        enabled: true   #开启页面表单的Rest功能

        用法: 表单method=post,隐藏域 _method=put

       1.2.改默认_method

@Configuration(proxyBeanMethods = false)
public class WebConfig {

    @Bean
    public HiddenHttpMethodFilter hiddenHttpMethodFilter(){
        HiddenHttpMethodFilter methodFilter = new HiddenHttpMethodFilter();
        methodFilter.setMethodParam("_m");
        return methodFilter;
    }
}

    3.2.普通参数与基本注解

        1.注解

@PathVariable、@RequestHeader、@ModelAttribute、@RequestParam、@MatrixVariable、@CookieValue、@RequestBody

@RestController
public class ParameterTestController {


    //  car/2/owner/zhangsan
    @GetMapping("/car/{id}/owner/{username}")
    public Map getCar(@PathVariable("id") Integer id,
                                     @PathVariable("username") String name,
                                     @PathVariable Map pv,                                    
                                     @RequestHeader Map header,                                    
                                     @RequestParam Map params,
                                     @CookieValue("_ga") String _ga,
                                     @CookieValue("_ga") Cookie cookie){

        Map map = new HashMap<>();
        return map;
    }
}

        2.Servlet API

        3.复杂参数

        4.自定义对象参数

    3.3. POJO封装过程

    3.4 参数处理原理

  4 数据响应与内容协商

  5 视图解析与模板引擎

    5.1 视图解析

    5.2 模板引擎-Thymeleaf

    5.3 thymeleaf使用

        1.引入Starter


  org.springframework.boot
  spring-boot-starter-thymeleaf

        2. 虚拟路径

server:
  servlet:
    context-path: /word

        3.

     5.4 构建后台管理系统

  6 拦截器

    6.1 HandlerInterceptor 接口

@Slf4j
public class LoginInterceptor implements HandlerInterceptor { 
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 
            return true; 
    }

  
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("postHandle执行{}",modelAndView);
    }
 
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("afterCompletion执行异常{}",ex);
    }
}

    6.2 配置拦截器

/**
 * 1、编写一个拦截器实现HandlerInterceptor接口
 * 2、拦截器注册到容器中(实现WebMvcConfigurer的addInterceptors)
 * 3、指定拦截规则【如果是拦截所有,静态资源也会被拦截】
 */
@Configuration
public class AdminWebConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/**")  //所有请求都被拦截包括静态资源 
    }
}

    6.3 拦截器原理

  7 文件上传

    7.1 页面表单


    7.2 文件上传代码

@Slf4j
@RestController
public class FileController {

    @PostMapping("/upload")
    public String upload(UploadInfo info)
    {
        try {
            MultipartFile file = info.getFile();
            if(!file.isEmpty())
            {
               String fileName = file.getOriginalFilename();
               file.transferTo(new File("E:\\cache\\" + fileName));
            }
            System.out.println(info.getUserName());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return "success";
    }
}

    7.3 自动配置原理

        1.修改大小

spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=100MB

  8 异常处理

    8.1 默认规则

        Spring Boot提供/error处理所有错误的映射,只要在这个目录下放相应的错误代码文件即可

    8.2 定制错误处理逻辑

        error/404.html   error/5xx.html;有精确的错误状态码页面就匹配精确,没有就找 4xx.html;如果都没有就触发白页

  9 Web原生组件注入

    9.1 使用Servlet API

        1. Servlet、Filter、Listener

        2. 9.2 使用Servlet API

@ServletComponentScan(basePackages = "com.atguigu.admin") :指定原生Servlet组件都放在那里
@WebServlet(urlPatterns = "/my"):效果:直接响应,没有经过Spring的拦截器?
@WebFilter(urlPatterns={"/css/*","/images/*"})
@WebListener

    9.2 使用RegistrationBean   

        1.ServletRegistrationBeanFilterRegistrationBean, ServletListenerRegistrationBean

@Configuration
public class MyRegistConfig {

    @Bean
    public ServletRegistrationBean myServlet(){
        MyServlet myServlet = new MyServlet();

        return new ServletRegistrationBean(myServlet,"/my","/my02");
    }


    @Bean
    public FilterRegistrationBean myFilter(){

        MyFilter myFilter = new MyFilter();
//        return new FilterRegistrationBean(myFilter,myServlet());
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(myFilter);
        filterRegistrationBean.setUrlPatterns(Arrays.asList("/my","/css/*"));
        return filterRegistrationBean;
    }

    @Bean
    public ServletListenerRegistrationBean myListener(){
        MySwervletContextListener mySwervletContextListener = new MySwervletContextListener();
        return new ServletListenerRegistrationBean(mySwervletContextListener);
    }
}

  10 嵌入式Servlet容器

        10.1 TomcatWebServer, JettyWebServer,  NettyWebServer,  UndertowWebServer

  11 定制化原理

5.数据访问

  5.1 HikariDataSource

      1. 导入JDBC场景


    org.springframework.boot
    spring-boot-starter-data-jdbc


   mysql
   mysql-connector-java
   5.1.49

      2.修改配置项

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/db_account
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver

      3.测试

@Slf4j
@SpringBootTest
class Boot05WebAdminApplicationTests {

    @Autowired
    JdbcTemplate jdbcTemplate;


    @Test
    void contextLoads() { 
        Long aLong = jdbcTemplate.queryForObject("select count(*) from account_tbl", Long.class);
        log.info("记录总数:{}",aLong);
    }

}

  5.2 Druid数据源

    0.druid官方github地址

https://github.com/alibaba/druid

    1.创建数据源 


            com.alibaba
            druid
            1.1.17

    2.创建配置类

@Configuration
public class DruidDataSourceConfig {

    @ConfigurationProperties("spring.datasource")
    @Bean
    public DataSource dataSource()
    {
        DruidDataSource druidDataSource = new DruidDataSource();
        return druidDataSource;
    }
}

    3.测试

 Connection connection = dataSource.getConnection();

String sql = "select count(1) as c from t_user";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next())
{
   int name = resultSet.getInt("c");
   log.info("" + name);
}
resultSet.close();
connection.close();

    4.StatViewServlet  提供监控信息展示的html页面

@Configuration
public class DruidDataSourceConfig {

    @ConfigurationProperties("spring.datasource")
    @Bean
    public DataSource dataSource()
    {
        try {
            DruidDataSource druidDataSource = new DruidDataSource();
            druidDataSource.setFilters("stat,wall"); //开启监控,防火墙
            return druidDataSource;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /*
    * 配置druid的监控页面
    * */
    @Bean
    public ServletRegistrationBean statViewServlet(){

        StatViewServlet statViewServlet = new StatViewServlet();
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(statViewServlet,"/druid/*");
        return servletRegistrationBean;
    }
}

    5.使用官方starter方式,引入druid-starter

 
        com.alibaba
        druid-spring-boot-starter
        1.1.17
 

    6.配置文件

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/db_account
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver

    druid:
      aop-patterns: com.atguigu.admin.*  #监控SpringBean
      filters: stat,wall     # 底层开启功能,stat(sql监控),wall(防火墙)

      stat-view-servlet:   # 配置监控页功能
        enabled: true
        login-username: admin
        login-password: admin
        resetEnable: false

      web-stat-filter:  # 监控web
        enabled: true
        urlPattern: /*
        exclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*'


      filter:
        stat:    # 对上面filters里面的stat的详细配置
          slow-sql-millis: 1000
          logSlowSql: true
          enabled: true
        wall:
          enabled: true
          config:
            drop-table-allow: false

  5.3 MyBatis数据源

        1.引用 mybatis.org/mybatis-3/zh/getting-started.html


   org.mybatis.spring.boot
   mybatis-spring-boot-starter
   2.1.4
 

        2.配置模式

        application.yaml

mybatis:
  config-location: classpath:mybatis/mybatis-config.xml  #全局配置文件位置
  mapper-locations: classpath:mybatis/mapper/*.xml  #sql映射文件位置

        mapper文件

        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">


   

        3.注解模式

@Mapper
public interface CityMapper {

    @Select("select * from city where id=#{id}")
    public City getById(Long id);

    public void insert(City city);

}

        4.混合模式

  5.4 MyBatis-Plus

  5.5 Redis

6.单元测试

你可能感兴趣的:(java,java)