springboot: induction integration, the overall application framework and plug-ins recommended

Two days ago, Damon is probably the situation will springboot tell you a lot, and today Damon just as we talk about some of springboot integration framework, as well as some practical plug-introduction, I hope you like it. (Recently due to training more tired [now 10] has been very eye astringent, so the daily recommendation is relatively slow, I hope you forgive me.)

Spring Boot integration druid

  • druid has many configuration options, use Spring Boot Configuration files can be easily configured druid.

  • In application.yml write the configuration file:

  •   spring:
          datasource:
              name: test
              url: jdbc:mysql://192.168.16.137:3306/test
              username: root
              password:
              # 使用druid数据源
              type: com.alibaba.druid.pool.DruidDataSource
              driver-class-name: com.mysql.jdbc.Driver
              filters: stat
              maxActive: 20
              initialSize: 1
              maxWait: 60000
              minIdle: 1
              timeBetweenEvictionRunsMillis: 60000
              minEvictableIdleTimeMillis: 300000
              validationQuery: select 'x'
              testWhileIdle: true
              testOnBorrow: false
              testOnReturn: false
              poolPreparedStatements: true
              maxOpenPreparedStatements: 20
    复制代码
  • Here by type: com.alibaba.druid.pool.DruidDataSource configuration can be!

Spring Boot Integration MyBatis

  • Spring Boot integrates MyBatis, there are two ways, one simple way is to use MyBatis official offer: mybatis-spring-boot-starter
  • Another way is still a similar configuration mybatis-spring, this approach need to write some code yourself, but you can easily control the configuration of MyBatis.

mybatis-spring-boot-starter mode

  • In pom.xml to add a dependency:

  • org.mybatis.spring.boot mybatis-spring-boot-starter 1.0.0
  • mybatis-spring-boot-starter dependency tree as follows:

  • Which mybatis using version 3.3.0, you can:

  • <Mybatis.version> 3.3.0 </mybatis.version> Properties to modify the default versions.
  • mybatis-spring using version 1.2.3, you can:
  • <Mybatis-spring.version> 1.2.3 </mybatis-spring.version> modify the default versions.
  • Increase the allocation in application.yml in:

  • mybatis: mapperLocations: classpath:mapper/*.xml typeAliasesPackage: tk.mapper.model

  • In addition to the above two common configurations are:

  • mybatis.config: mybatis-config.xml file path configuration
  • mybatis.typeHandlersPackage: scanning package typeHandlers
  • mybatis.checkConfigLocation: Check the configuration file exists
  • mybatis.executorType: set the execution mode (SIMPLE, REUSE, BATCH), the default is SIMPLE

mybatis-spring fashion

  • Usage in this manner and the usual closer. We need to add mybatis dependency and mybatis-spring-dependent.

  • Then create a MyBatisConfig configuration class:

      	/**
      	 * MyBatis基础配置
      	 *
      	 * @author liuzh
      	 * @since 2015-12-19 10:11
      	 */
      	@Configuration
      	@EnableTransactionManagement
      	public class MyBatisConfig implements TransactionManagementConfigurer {
      	    @Autowired
      	    DataSource dataSource;
      	
      	    @Bean(name = "sqlSessionFactory")
      	    public SqlSessionFactory sqlSessionFactoryBean() {
      	        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
      	        bean.setDataSource(dataSource);
      	        bean.setTypeAliasesPackage("tk.mybatis.springboot.model");
      	
      	        //分页插件
      	        PageHelper pageHelper = new PageHelper();
      	        Properties properties = new Properties();
      	        properties.setProperty("reasonable", "true");
      	        properties.setProperty("supportMethodsArguments", "true");
      	        properties.setProperty("returnPageInfo", "check");
      	        properties.setProperty("params", "count=countSql");
      	        pageHelper.setProperties(properties);
      
              //添加插件
              bean.setPlugins(new Interceptor[]{pageHelper});
      
              //添加XML目录
              ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
              try {
                  bean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
                  return bean.getObject();
              } catch (Exception e) {
                  e.printStackTrace();
                  throw new RuntimeException(e);
              }
          }
          @Bean
          public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
              return new SqlSessionTemplate(sqlSessionFactory);
          }
      
          @Bean
          @Override
          public PlatformTransactionManager annotationDrivenTransactionManager() {
              return new DataSourceTransactionManager(dataSource);
          }
      }
    复制代码
  • The above code creates a SqlSessionFactory and a SqlSessionTemplate, to support annotation services, increased @EnableTransactionManagement notes, and in return a PlatformTransactionManagerBean.

  • Also should be noted that this configuration is not MapperScannerConfigurer, if we want to scan the MyBatis Mapper interface, we need to configure this class, we need to put this configuration in a separate class.

      /**
       * MyBatis扫描接口
       * 
       * @author liuzh
       * @since 2015-12-19 14:46
       */
      @Configuration
      //注意,由于MapperScannerConfigurer执行的比较早,所以必须有下面的注解
      @AutoConfigureAfter(MyBatisConfig.class)
      public class MyBatisMapperScannerConfig {
          @Bean
          public MapperScannerConfigurer mapperScannerConfigurer() {
              MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
              mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
              mapperScannerConfigurer.setBasePackage("tk.mybatis.springboot.mapper");
              //配置通用mappers
      Properties properties = new Properties();
              properties.setProperty("mappers", "tk.mybatis.springboot.util.MyMapper");
              properties.setProperty("notEmpty", "false");
              properties.setProperty("IDENTITY", "MYSQL");
              //这里使用的通用Mapper的MapperScannerConfigurer,所有有下面这个方法
              mapperScannerConfigurer.setProperties(properties);
      
              return mapperScannerConfigurer;
          }
      }
    复制代码
  • This configuration must pay attention to @AutoConfigureAfter (MyBatisConfig.class), you must have this configuration, otherwise there will be an exception. The reason is that this class performed earlier, due sqlSessionFactory not exist, subsequent execution error. After doing the above configuration can use the MyBatis.

About pagination plug-in integration and common Mapper

  • Examples of the plug-in plug tabs are in the above code.
  • General Mapper is the time to configure the actual configuration MapperScannerConfigurer use - tk.mybatis.spring.mapper.MapperScannerConfigurer can configure properties using Properties.

Spring Integration MyBatis of infrastructure projects Boot

  • Paging Universal Plug and related information Mapper can be found through the above address.

Spring Boot static resource handling

  • Spring Boot default handling would have been sufficient, Spring Boot various attributes WebMvcAutoConfiguration configured by default.

  • Spring Boot is recommended to use the default processing mode, you need to configure their own place can be modified through the configuration file.

  • But if you want full control of Spring MVC, you can add notes on @Configuration configuration class @EnableWebMvc, after the increase in notes WebMvcAutoConfiguration configuration will not take effect, you need to configure each of their own needs. Configuration in this case the proposed reference WebMvcAutoConfiguration class. - The following article for Spring Boot default approach, part of the configuration by setting the application.yml profile. -.spring boot file is loaded default path

      /META-INF/resources/ 
      /resources/ 
      /static/ 
      /public/
      private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {  
              "classpath:/META-INF/resources/", "classpath:/resources/",  
              "classpath:/static/", "classpath:/public/" };  
    复制代码
  • All local static resources are configured in the classpath the following, rather than in the webapp under the

Configuring resource mapping

  • Spring Boot default configuration / ** mapped to / static (or / public, / resources, / META-INF / resources), / webjars / ** mapped to
  • classpath:/META-INF/resources/webjars/。
  • NOTE: The above / static directory, etc. are in the classpath: below.

  • If you want to add, such as / mystatic / ** mapped to the classpath: / mystatic /, you can make your configuration class inherited WebMvcConfigurerAdapter, then rewritten as follows:

      @Override
      public void addResourceHandlers(ResourceHandlerRegistry registry) {
          registry.addResourceHandler("/mystatic/**")
                  .addResourceLocations("classpath:/mystatic/");
      }
    复制代码
  • This approach will increase in default on the basis of / mystatic / ** mapped to the classpath: / mystatic /, does not affect the default mode, can be used simultaneously.
  • There is also a static resource mapping configuration options, here for simplicity written in .properties way: spring.mvc.static-path-pattern = / ** # Path pattern used for static resources this will affect the default configuration of / **, for example. after modify / static / **, only map as /static/js/sample.js such a request (before modification is /js/sample.js). This configuration can only write one value, unlike most can configure multiple separated by commas.

Caution

  • For example, a directory structure as follows:

      └─resources
          │  application.yml
          │
          ├─static
          │  ├─css
          │  │      index.css
          │  │
          │  └─js
          │          index.js
          │
          └─templates
                  index.ftl
    复制代码
  • How to reference a static resource in index.ftl above it in?

  • The following wording:

  • Note: The default configuration / ** mapped to / static (or / public, / resources, / META-INF / resources)

  • When the request /css/index.css, Spring MVC can be found at / static / directory.

  • If the configuration is /static/css/index.css, then several directories are not following the above configuration / static directory, and therefore can not find the resource file!

  • So write static resource position, do not put the name of the directory map (such as / static /, / public /, / resources /, / META-INF / resources /)!

Use WebJars

  • WebJars: www.webjars.org/

  • For example jquery, add dependencies:

    org.webjars jquery 1.11.3
  • You may then be used as follows:

  • You may notice that version 1.11.3 of the href, if only so used, then when we have to switch manually modified version of href, strange trouble, we can solve the following manner.

  • First add a dependency in pom.xml:

    org.webjars webjars-locator
  • Add a WebJarController:

      @Controller
      public class WebJarController {
          private final WebJarAssetLocator assetLocator = new WebJarAssetLocator();
      
          @ResponseBody
          @RequestMapping("/webjarslocator/{webjar}/**")
          public ResponseEntity locateWebjarAsset(@PathVariable String webjar, HttpServletRequest request) {
              try {
                  String mvcPrefix = "/webjarslocator/" + webjar + "/";
                  String mvcPath = 
      (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
                  String fullPath = 
      assetLocator.getFullPath(webjar, mvcPath.substring(mvcPrefix.length()));
                  return new ResponseEntity(new ClassPathResource(fullPath), HttpStatus.OK);
              } catch (Exception e) {
                  return new ResponseEntity<>(HttpStatus.NOT_FOUND);
              }
          }
      }
    复制代码
  • When then used as follows:

  • Note: There is no need to write the version number, but pay attention to when writing url, just remove the version number in the original url, based on other Less!

Static version resource management

  • Spring MVC provides a functional version of the mapping of static resources.

  • Purpose: When we change the content of the resource, because the browser cache, the user's local static resources or old resources, in order to prevent problems caused by this situation, we may manually add a version number or other means at the time of the request url .

  • The version number such as:

  • Spring MVC provides functionality can easily help us solve similar problems.

  • Spring MVC, there are two solutions.

  • Note: The following template configuration for freemarker way, other configurations can refer to.

Resource name -md5 way

<link rel="stylesheet" type="text/css" href="/css/index-2b371326aa93ce4b611853a309b69b29.css">
复制代码
  • Spring will automatically read resource md5, and then add the name to the back of index.css, so when the resource content changes, the file name changes, will update the local resources.
  • Configuration:
  • Application.properties in the following configurations:

  • spring.resources.chain.strategy.content.enabled=true spring.resources.chain.strategy.content.paths=/**

  • After such configuration, all / * static resource requests will be processed to look like the above example.

  • Does not end here, we write resources url is even a special treatment.

  • First, add the following configuration:

  • @ControllerAdvice public class ControllerConfig { @Autowired ResourceUrlProvider resourceUrlProvider; @ModelAttribute("urls") public ResourceUrlProvider urls() { return this.resourceUrlProvider; } }

  • Then the time to write a page with the following wording:

  • Use urls.getForLookupPath ( '/ css / index.css') to obtain a resource name after the treatment.

The version number of ways

  • Application.properties in the following configurations:

  • spring.resources.chain.strategy.fixed.enabled=true spring.resources.chain.strategy.fixed.paths=/js/,/v1.0.0/ spring.resources.chain.strategy.fixed.version=v1.0.0

  • This configuration requires special attention, the value of the version is arranged in the paths.

  • In page write, worded as follows:

    • Note that this is still used urls.getForLookupPath, urls configuration see above way. In the actual page request, it will appear as:

    • Here you can see the address /v1.0.0/js/index.js.

    Static version resource management process

    • First calls urls.getForLookupPath Freemarker template method returns a /v1.0.0/js/index.js or /css/index-2b371326aa93ce4b611853a309b69b29.css.
    • At this time the content on the page is a resource address after processing. After this browser to initiate a request.
    • He said separately here.
    The first way md5
    • Request /css/index-2b371326aa93ce4b611853a309b69b29.css, we md5 configured paths = / **, so Spring MVC attempts to contain the url -, if included will remove this part of the back, and then mapped to the directory (e.g., / static /) find /css/index.css file, if you can find returns.
    The second version of the way
    • Request /v1.0.0/js/index.js.
    • If we paths are not configured /v1.0.0, then the above address request will not be processed by way version, and therefore can not find the resources above.
    • If you configure /v1.0.0,Spring will remove the /v1.0.0 look for /js/index.js, will eventually be found in / static / below.

    to sum up:

    As a new program ape, Damon hopes to progress together with you. Article or inadequacy described elsewhere, we hope to raise a lot of progress together.

    Damon will continue to explore some useful advice, knowledge and new tools to share with you, thank you!

    Past articles are uploaded to github, there is little interest in Star partner can under: github.com/xxxyyh/Fron...

Guess you like

Origin juejin.im/post/5d6688006fb9a06af7124683