Spring supplementary knowledge

1. You don’t need to do it again for the things downloaded by maven

Just import maven, we have to download it again after each import. After setting this, the jar package is imported in maven for the first time and saved locally, and the local one is used directly after the second use (but Occupy memory)
Insert picture description here

2、@RequestBody与@ResponseBody

For memo

  • @ResponseBody is used to return data to the front end in the form of JSON, where @RestController=@ResponseBody+@Controller
  • @RequestBody The user front-end returns the data to the back-end, but the format of the front-end to the back-end is JSON, which is generally used for processing
//有Book对象,将前端返回来的JSON数据转换成Book对象(自动识别的)
 @PostMapping("/")
    public int insertBook(@RequestBody  Book book){
    
    
        return bookService.insertBook(book);
    }

Therefore, if you accept front-end data, each received data is a class.
But one thing to note is that you can write directly to Map instead of writing an object, but it will not

3、@Bean

Now I understand what @Bean does. For example, I have a IdWorkercustom class. To add this class to the IOC container is to add it to the spring collection. This thing is neither a control class nor a configuration class. Why? Join?

Just find a place @Bean and return the class.

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

	//加入IOC容器中
    @Bean
    public IdWorker idWorker(){
    
    
        return new IdWorker();
    }
}

4 、 @ CrossOrigin

Used before the control class, used for cross-domain requests, that is, each distributed port is different and needs to be added

5、@RequestMapping

When @RequestMapping is used in front of a class, it means that the access path must be added with the parameters of the class, but it is worth mentioning! ! ! After the class uses @RequestMapping, do not add the path in the method/


@RestController
@RequestMapping("/test")
public class testController {
    
    

    @Autowired
    private LabelService labelService;

    @GetMapping("abc")
    public List<Label> test(){
    
    
        return labelService.findAll();
    }
}

Visit http://localhost:8080/test/abc to get the data

(But in the projects I did before, method addition /is also possible, the code is really amazing things)

6 、 @ CrossOrigin

Before being used for control classes, cross-domain requests can be made, generally used for distributed structures

7, pojo, @Entity, @Table, Serializable serialization

1) pojo

What is pojo?
Add @ResponseBody directly to the data from the backend to the frontend to pass the object programming JSON to the frontend.
But the front-end transmits data to the back-end, and the back-end gets the data must be an object, this object is called pojo (Plain Ordinary Java Object)

2)@Entity

Generally, @Entity must be added to the pojo of JPA. I don’t understand and I don’t know where to find the answer.

3)@Table

I have learned @Table before, JPA exclusive, the object structure and the table structure should be the same.

4) Serializable serialization

Generally speaking, pojo classes are required implements Serializable, because the front-end is returned. Although the Result class is fixed, the pojo class of the data data may be an array or a single object, which is not specified. And the pojo data will be seen by the front end, and the status codes of the Result class do not need to be shown to the user, so the class shown to the user implements Serializableis the right one.

@Entity
@Table(name = "tb_label")
@Data
public class Label implements Serializable {
    
    
    @Id
    private String id;
    private String labelname;//标签名称
    private String state;//状态
    private Long count;//使用数量
    private Long fans;//关注数
    private String recommend;//是否推荐
}

8、@Transactional

Put in front of the server layer class to ensure the integrity of the database transaction

9、@RestControllerAdvice、@ExceptionHandler

This exception can be handled globally, and is often used in conjunction with @ExceptionHandler. See details

https://www.cnblogs.com/lenve/p/10748453.html

@RestControllerAdvice
public class BaseExceptionHandler {
    
    

    @ExceptionHandler(Exception.class)
    public Result exception(Exception e){
    
    
        e.printStackTrace();
        return new Result(false, StatusCode.ERROR,e.getMessage());
    }
}

10.Quick input parameters, return structure:/**+回车

Insert picture description here
Carriage return
Insert picture description here

11. Case insensitive prompt

https://jingyan.baidu.com/article/d621e8daca64d96864913f09.html

12、@Transactional

When unit testing occurs not session, add @Transactionalannotations to the unit test class

13. To use object navigation query in JPA, use @JsonIgnoreProperties

In the case of one-to-many, the two classes have their own, this time we must add before the foreign key attribute@JsonIgnoreProperties(value = {"另一类的外键属性名(主表的写Set属性名,从表的写主表类属性名)"})

public class Employee {
    
    

    @ManyToOne(targetEntity = Company.class,fetch = FetchType.LAZY)
    @JoinColumn(name = "employee_company_id",referencedColumnName = "company_id")
    @JsonIgnoreProperties(value = {
    
    "employees"})
    private Company company;//这个名字
}
public class Company {
    
    

    @OneToMany(mappedBy = "company",cascade = CascadeType.ALL,fetch = FetchType.LAZY)//mappedBy参数写从表中外键的属性名
    @JsonIgnoreProperties(value = {
    
    "company"})
    private Set<Employee> employees = new HashSet<>();//这个名字

}

14. There are keywords in the table column

Keyword table: https://blog.csdn.net/findmyself_for_world/article/details/43225555
Solution: https://blog.csdn.net/lose_alan/article/details/105510504

15、@Component

Before the class, add the class to the container. Almost all classes of spring are added to the container to process by themselves. The three-tier architecture and the entity layer are also added to the container.

16. Time conversion format

If new Date, the format is like this Fri Nov 27 16:25:02 CST 2020
conversion

String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
System.out.println(date);

2020-11-27 16:18:09

17. Add the class to the container

1) @Component

Add @Component in front of the class, when using @Autowired, 类名 名it will be automatically imported

2) No @Component

In the main program

@Bean
public 类 类名(){
    
    
	return new;
}

Use is also @Autowired

18. Configuration class and yml

It is a configuration class, and then the parameters want to be written in application.yml, so it is more convenient to change

1) @Value("${分级设计}")Write before the attribute

@Component
public class SmsListener {
    
    

    //从yml自动拿去数据
    @Value("${aliyun.sms.sign_name}")
    private String sign_name;//签名

    @Value(("${aliyun.sms.template_code}"))
    private String template_code;//模板编号
}
aliyun:
  sms:
    sign_name: 十次方1024博客
    template_code: SMS_205826458

2) @ConfigurationProperties("分级设置")Write before the class

@ConfigurationProperties("jwt.config")
public class JwtUtil {
    
    

    private String key ;

    private long ttl ;//一个小时
}
jwt:
  config:
    key: tensquare
    ttl: 360000

19. Message header

Automatic injection

	@Autowired
	private HttpServletRequest request;

Get header information

	//获取key为Authorization的消息头
	String authHeader = request.getHeader("Authorization");

	//获取key为claims_admin的消息头
	String token = (String) request.getAttribute("claims_admin");
  • The two are not the same: you can get the header where the former is. The latter is the Java program through request.setAttribute(下标,值)to set the value, and then only through getAttribute()to get. I don't know if it is specific. . .

Add header message

request.setAttribute("claims_admin",token);

20, cross-domain processing

Don't ask, i don't know

@Configuration
public class CrosConfig implements WebMvcConfigurer {
    
    
    @Override
    public void addCorsMappings(CorsRegistry registry) {
    
    
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET","HEAD","POST","DELETE","OPTIONS","PUT")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }
}

Guess you like

Origin blog.csdn.net/yi742891270/article/details/109266645