SpringBoot Basic Knowledge and Project Construction

Keywords: Spring Redis Druid Mybatis

Overview of SpringBoot
background
  • Springboot uses (conventions are greater than configurations). There are a lot of configurations in the project. In addition, some customary configurations are built in, which greatly reduces our workload. Spring boot makes it easy to create a spring framework-based project that runs independently (running jar, built-in servlet container), quasi-production, and we don't even need very little spring configuration with spring boot

  • Characteristic

    • Create a stand-alone Spring application
    • Embedded Tomcat, without deploying WAR files
    • Simplified Maven configuration
    • Automatically configure Spring
    • Provide production ready functions such as indicators, health checks and external configuration
    • Absolutely no code generation and no configuration requirements for XML
    • Configuration philosophy: zero profile, annotation and JavaConfig exposed bean s
  • Advantage

    • Quick Building Projects
    • Seamless integration of mainstream frameworks
    • Projects can run independently without relying on external servlet containers
    • Provide runtime application monitoring
    • Greatly improved development and deployment efficiency
    • Easy integration with Docker containers, etc.
Environmental Construction
  • Auto-build
    • demo code can be generated directly using https://start.spring.io/.
    • Using the tools in idea to build a project
Manual construction
  • Recommend standard maven projects, add spring boot parent dependencies
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.21.RELEASE</version>
        <relativePath/>
    </parent>
  • Add module dependencies based on the project to be built
         <!--
            Web Modular springboot All relevant dependencies will be added together
        -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--
            Hot Deployment Plug-ins for Automatic Refresh
        -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
  • Create a project startup class (to start the overall spring boot project)
  • @ In addition to basic annotations, SpringBoot Application contains three additional annotations
    • Spring Boot Configuration: Inherited @Configuration, which is equivalent to the beans node in the Spring configuration
    • Enable AutoConfiguration: Allows Spring containers to inject dependencies based on declared bean s
    • ComponentScan: The path of the package to be scanned as specified in the original configuration file
@SpringBootApplication(scanBasePackages = "com.ck")
public class Starter {

    public static void main (String[] args){

        SpringApplication.run(Starter.class,args);

    }
}
  • All configuration information in the project is configured in a unique configuration file, application.properties or application.yaml
  • Specific Configuration Reference Configuration Items
Integrated JSP
  • Adding dependencies
    <dependency>
      		<groupId>org.apache.tomcat.embed</groupId>
      		<artifactId>tomcat-embed-jasper</artifactId>
      	</dependency>
      	<dependency>
      		<groupId>javax.servlet</groupId>
      		<artifactId>javax.servlet-api</artifactId>
      	</dependency>
      	<dependency>
      		<groupId>javax.servlet</groupId>
      		<artifactId>jstl</artifactId>
      	</dependency>
    
    
    • Create webapp directories (you can also create WEB-INF directories together)
    • Writing jsp pages
      • If you want to return the logical view name as a forward operation, you need to configure the view parser
#view resolver
#prefix
spring.mvc.view.prefix=/WEB-INF/jsp/
#Suffix
spring.mvc.view.suffix=.jsp

Integrated DRUID Data Source
  • For x xxx-starter dependencies provided in SpringB oot, SpringB OOT automatically creates some JavaBean objects in dependencies based on import dependencies
  • But if SpringBoot does not provide its corresponding starter dependencies for some Bean objects, they need to be created manually (through JavaConfig or XML can be defined and introduced through annotations)
  • DRUID is configured using JavaConfig
  • Adding dependencies
<!--
    DRUID
 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.8</version>
</dependency>
<!--
    MySQL drive
-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

  • Configure connection pool parameters
  • Add a DRUID configuration class
    • Configuring Druid data sources through JavaConfig
    • @ Configuration is equivalent to adding a bean definition to the beans node
    • @ The return result of the bean method is equivalent to a bean object.
    • @ Configuration Properties finds the names of all configuration items after matching prefixes
/**
 * Configuring Druid data sources through JavaConfig
 */
//This is equivalent to adding a bean definition to the beans node
@Configuration
public class DruidConfig {
    //Equivalent to a bean node, it is usually written in a method
    //After the method is executed, the method returns the same result as a bean object.
    //Registered in Spring Container
    @Bean
    //After the method is executed, you get a DruidDataSource object
    //But attributes in objects have not yet been assigned
    //Find the name of the configuration item after all matching prefixes through the @Configuration Properties annotation
    //To find the set method of set + configuration item in bean object, inject attribute value into instance through set
    //At this point, the initialization of the data source object is completed.
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource initDataSource() {
        //Creating Data Source Objects from Java Code
        DruidDataSource ds = new DruidDataSource();
        return ds;
    }
}

Integrating MyBatis
  • Adding dependencies
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.0.0</version>
</dependency>

  • Specify the path of the mapping file
    • mybatis.mapper-locations=classpath:mapper/*.xml
  • You need to specify the path of the mapper interface
    • Here you need to load the annotation @MapperScan("com.sy.mapper") in starter.
  • Configure some MyBatis framework parameters: alias, cache, underscore and hump mapping
    • mybatis.type-aliases-package=com.sy.entity
Integrated Redis
  • Adding dependencies
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-redis</artifactId>
    <version>1.4.3.RELEASE</version>
</dependency>

  • Add redis configuration information
#Relevant configuration of redis
#Host
spring.redis.host=192.168.174.101
#port
spring.redis.port=6379
#Default database
spring.redis.database=0
#Password
#spring.redis.password=
#Connection pool parameters
spring.redis.pool.max-idle=20
spring.redis.pool.min-idle=1
spring.redis.pool.max-active=20
spring.redis.pool.max-wait=60000

  • Configure RedisTemplate
    • RedisConnectionFactory objects are automatically created when dependencies are introduced
    • This is equivalent to automatically injecting it into the method parameters from the container.
@Configuration
public class RedisConfig {

    /**
     * RedisConnectionFactory Objects are automatically created when dependencies are introduced
     * So here it's equivalent to automatically injecting it into the method parameters from the container.
     */
    @Bean
    public RedisTemplate getRedisTempalte(RedisConnectionFactory connectionFactory) {
        RedisTemplate redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(connectionFactory);
        return redisTemplate;
    }
}


  • Use RedisTemplate to operate Redis in Spring
@RequestMapping(value = "redis", method = RequestMethod.GET)
public String redis() {
    Boolean result = (Boolean) redisTemplate.execute(new RedisCallback<Boolean>() {
        @Override
        public Boolean doInRedis(RedisConnection con) throws DataAccessException {
            con.set("name".getBytes(), "Tom".getBytes());
            return true;
        }
    });
    System.out.println(result);
    return "hello";
}

Integrated interceptor
  • Write interceptor class
    • For interceptors, filters, listeners, cross-domain access to a range of web-related content can be accomplished in a configuration class that requires the implementation of the WebMvcConfigurer interface
  • Add the configuration of interceptor to the configuration class that implements the WebMvcConfigurer interface
    • Multiple interceptors can be registered in this method. The interception path and exclusion path in the interceptor are variable length parameters.
      The order of interception is in the order of registration.
@Override
public void addInterceptors(InterceptorRegistry registry) {
    //Register the interceptor here
    registry.addInterceptor(new MyInterceptor01()).addPathPatterns("/**").excludePathPatterns("/hello02");
}

File upload
  • Add parameters related to file upload (you'll start instantiating the file upload component here)
  • Other operations are the same
#Maximum size of a single file
spring.http.multipart.max-file-size=1024Mb
#Maximum size of all files added up at request
spring.http.multipart.max-request-size=2028Mb

Cross-domain access

Configure in the configuration class that implements the WebMvcConfigurer interface

public void addCorsMappings(CorsRegistry registry) {
    //Setting cross-domain
registry.addMapping("/**").allowedMethods("*").allowedOrigins("*").allowedHeaders("*").allowCredentials(true);
}

Filters, monitors
  • Edit filters and listeners
  • Configure in the configuration class that implements the WebMvcConfigurer interface
adopt@Bean Annotations are exposed
 /**
     * Configure filters
     */
    @Bean
    public FilterRegistrationBean addFilter01() {
        FilterRegistrationBean regist = new FilterRegistrationBean();
        regist.setFilter(new Filter01());
        regist.addUrlPatterns("/*");
        //Initialization parameters
//        regist.setInitParameters();
        //Filtration sequence of filters
        //Priority: The smaller the value, the higher the priority
        //regist.setOrder();
        return regist;
    }

    /**
     * Configuration listener
     */
    @Bean
    public ServletListenerRegistrationBean addListener() {
        ServletListenerRegistrationBean listener = new ServletListenerRegistrationBean();
        listener.setListener(new MyContextListener());
        return listener;
    }

Exception handler
  • Matching with Spring MVC
@Component
public class MyExceptionHandler implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
                                         Exception ex) {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("500");
        mv.addObject("errMsg", ex.getMessage());
        return mv;
    }
}

Posted by Javizy on Thu, 25 Jul 2019 23:58:06 -0700