SpringBoot-Common Annotations-Spring03

SpringBoot-Common Annotations-Spring03

@Configration and @Bean

@Configration->beans tag

@Bean ->bean tag

id=method name|name attribute in comments (higher priority after specified)

class = "Method's return result

package com.example.firstspringboot.config;

import com.example.firstspringboot.entity.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration  //代表当前类是个配置类
public class UserConfig {

    @Bean  //构建1个实例,放到spring容器中
    public User user() {
        User user = new User();
        user.setId(1);
        user.setName("荣荣");
        return user;
    }
    
    /*
    <beans> @Configuration
    <bean id="user" class="com.example.firstspringboot.entity.User>
    </beans>   
     */
}

Start class annotation @SpringBootApplication

@SpringBootApplication is a combined annotation

@SpringConfigration is the @Configration annotation representing that the startup class is a configuration class

@EnableAutoConfiguration helps you realize automatic assembly. When the springbooot project starts, run a SpringFactoryLoader class to load the configuration classes (opened) under META-INF/spring factories through the load method in springfactoriesLoader, and load them one by one in the for loop

Benefits: To write a large amount of integrated information out of order, you only need to follow the good conventions provided by springboot to integrate

Disadvantage: starter dependency is added, and necessary configuration information needs to be filled in

Manually close @SpringBootApplication(exclude = QuartzAutoConfiguration.class)

@ComponentScan

Equivalent to <context:component-scan basePackage="package name"/>

Configuration file format

Support properties and yml, even json

Recommend yml

  • Manage positions based on line breaks and indentation
  • Lightweight

Disadvantages:

  • Strictly follow line breaks and indentation
  • When filling in value, be sure to add a space after the colon

Multi-environment configuration

Add a configuration item to the application.yml file

spring:
  profiles:
    active: dev

Create multiple application-environment name .yml files in the resource directory

When deploying the project, through java -jar jar file -spring.profiles.active=environment

Import external configuration file information

Like the traditional SSM method, the content of the properties.yml file is obtained through the annotation of @Value

If you need to write a lot of custom configurations in the yml file, with a unified prefix,

@ConfigurationProperties(prefix = "aliyun")
@Component
@Data
public class AliyunProperties {
    private String xxx;
    private String yyy;
    private String zzz;


}
aliyun:
  xxx: xxxxx
  yyy: yyyyy
  zzz: zzzzz

Hot reload

Import dependency

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <optional>true</optional>
</dependency>

Modify the configuration of setting

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-1uCGZ43D-1600395426952)(/Users/chenxiwen/Library/Application Support/typora-user-images/image-20200911231843480 .png)]

After modifying the content, you can rebuild the project through build

SpringBoot integrates Mybatis

  1. Import dependency

  2. Write configuration file

    2.1 Prepare the entity class

@Data
public class Subject implements Serializable {

  private long id;
  private long subjectNo;
  private String subjectName;
  
}

2.2 Prepare mapper interface

public interface ResultMapper {

    List<Result> findAll();

}

Add annotations to the startup class and scan the package where the Mapper interface is located

@SpringBootApplication(exclude = QuartzAutoConfiguration.class)
@MapperScan(basePackages = "com.example.firstspringboot.mapper")
public class FirstSpringbootApplication {

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

}

2.3 Prepare the mapping file

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.firstspringboot.mapper.ResultMapper">
<!--    List<Result> findAll();-->
    <select id="findAll" resultType="Result">
        select * from result
    </select>

</mapper>

2.4 Add yml file configuration information

#mybatis配置
mybatis:
#  扫描映射文件
  mapper-locations: classpath:mapper/*.xml
#  配置别名扫描的包
  type-aliases-package: com.example.firstspringboot.entity
#  开启驼峰映射配置
  configuration:
    map-underscore-to-camel-case: true

2.5 Specify the connection to the database

#连接数据库的信息
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql:///result
    username: root
    password: 123456
    type: com.alibaba.druid.pool.DruidDataSource

3. Test

Mapper interface right click-"goto" Test

Create a test class for the interface, in the test directory

Let the current test class inherit the FirstSpringbootApplicationTests test class (plus public)

When the driver version is high, the time zone needs to be added

Annotation method to integrate mybatis

  1. Create student Mapper interface
public interface StudentMapper {

    List<Student> findeAll();

}
  1. Add mybatis annotation (@insert @delete @update @select), the startup class needs to add MapperScan annotation

    public interface StudentMapper {
    
        @Select("select * from student")
        List<Student> findeAll();
    
        @Select("select * fromstudent where id = #{id}")
        Student findOne(@Param("id")  Integer id);
    
    }
    
  2. Test and see the executed sql statement

logging:
  level:
    com.example.firstspringboot.mapper: DEBUG
class StudentMapperTest extends FirstSpringbootApplicationTests {

    @Autowired
    private  StudentMapper studentMapper;

    @Test
    void findeAll() {
        List<Student> studentList = studentMapper.findAll();
        for(Student s:studentList){
            System.out.println(s);
        }

    }

    @Test
    void findOne() {
        Student student = studentMapper.findOne(1);
        System.out.println(student);
    }
}

springboot integrated paging assistant

  1. Import dependency

  2. <!--        pagehelper分页助手-->
            <dependency>
                <groupId>com.github.pagehelper</groupId>
                <artifactId>pagehelper-spring-boot-starter</artifactId>
                <version>1.2.5</version>
            </dependency>
    
  3. Test use

  4. @Test
    public void findByPage() {
        PageHelper.startPage(1, 2);
        List<Student> list = studentMapper.findAll();
        PageInfo<Student> pageInfo = new PageInfo<>(list);
        for (Student student : pageInfo.getList()) {
            System.out.println(student);
        }
    }
    

springboot import jsp

  1. Import dependency

  2. <!--        JSP核心引擎-->
            <dependency>
                <groupId>org.apache.tomcat.embed</groupId>
                <artifactId>tomcat-embed-jasper</artifactId>
            </dependency>
    <!--        JSTL-->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>jstl</artifactId>
            </dependency>
    

Create webap and WEB-INF storage directories to store jsp pages

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-VFjbMFHC-1600395426954)(/Users/chenxiwen/Library/Application Support/typora-user-images/image-20200917212024309) .png)]

Create a controller and specify the prefix and suffix of the view

@Controller
public class JspController {

    @GetMapping("/index")
    public String index(Model model) {
        model.addAttribute("name", "荣荣");
        return "index";
    }
}
#连接数据库的信息
spring:
  mvc:
    view:
      prefix: /WEB-INF/
      suffix: .jsp

springboot exercises

Guess you like

Origin blog.csdn.net/rr18758236029/article/details/108659981