Writing Spring tests with Kotlin

Preface Usually we write Spring projects using Java language for business development and Java for unit testing. But Java is not very efficient in writing test code due to its lengthy code, and we usually consider multiple scenarios when writing the test code, so the amount of code expands dramatically, which brings a lot of time wastage. The biggest headache is the MockMvc mock request test, Java does not support multi-line strings until 15, which leads to the need to splice line by line, which is very unintuitive to read and does not make good use of the Intellij IDEA injection language.

Tracking the SpringMVC request process

Overall flow All requests are intercepted to DispatcherServlet , which is also a Servlet , executing doService . Snapshot all the parameters in the request and set some objects in the framework to the request object. Call the doDispatch(request,response) method. Call the getHandler method to get the corresponding Handler. Call getHandlerAdapter to get the corresponding HandlerAdapter. Apply the interceptor’s PreHandler, or return it directly if the interceptor’s PreHandeler returns false.

Understanding HttpMessageConverter in Spring

Http Message Converter Introduction Http Message Converter is responsible for serializing Java Object to JSON/XML data representation and deserializing JSON/XML data representation to Java Object. When we configure: <mvc:annotation-driven /> in based XML or @EnableWebMvc in based Java (both are equivalent), AnnotationDrivenBeanDefinitionParser will register a series of conversion service, validators, and message-converters. If there is no custom <message-converters> tag in <mvc:annotation-driven />, Spring will register the following set of message-converters

Spring Security version 5.4 brings new ways to play

1. Preface In previous Spring Security tutorials we customize configuration by declaring a configuration class WebSecurityConfigurerAdapter and then overriding (@Override) the corresponding methods. However, all this has changed since Spring Security 5.4, since Spring Security 5.4 we don’t need to inherit from WebSecurityConfigurerAdapter in order to configure HttpSecurity. The original description reads. Remove need for WebSecurityConfigurerAdapter #8805 Configure HTTP Security without extending WebSecurityConfigurerAdapter #8804 issues/8804) 2. The new configuration method

Optimize Spring Boot application Docker images to improve CI/CD efficiency

More and more projects are containerized and Docker has become an important tool in software development. We can usually package the fat jar of a Spring Boot application as a docker image with the following Dockerfile. 1 2 3 4 5 FROM adoptopenjdk:8-jre-hotspot ARG JAR_FILE=target/*.jar COPY ${JAR_FILE} app.jar EXPOSE 8080 ENTRYPOINT ["java","-jar","/app.jar"] It looks good, but you will find that if we change the business code, the image will be

Spring Security Dynamic Permission Control could be a little simpler

Previously in the tutorial on dynamic permission control, we implemented dynamic permission control by customizing FilterInvocationSecurityMetadataSource and AccessDecisionManager two interfaces. There are more things we need to do here, and there is a certain learning cost. Today to introduce a more simple and easy to understand approach to implement dynamic permission control. Expression-based access control 1 2 3 httpSecurity.authorizeRequests() .anyRequest() .access("hasRole('admin')") Needless to say, after we configure the expression hasRole('admin'),

Spring Security filter chain system

While learning Spring Security did you have any of the following two questions. How is login configured in Spring Security? What is the access control mechanism for Spring Security? SpringBootWebSecurityConfiguration The answers to the above two questions are in the configuration class SpringBootWebSecurityConfiguration. You can follow this mind map to understand it. This auto-configuration: SpringBootWebSecurityConfiguration provides a default set of Spring Security configurations for Spring Boot applications. 1 2 3

How to elegantly read and write HttpServletRequest and HttpServletResponse request bodies

Recently, many interactions have to deal with the native HttpServletRequest and HttpServletResponse. Read body data from HttpServletRequest and encapsulate it into some kind of data structure; write data to HttpServletResponse and respond. The traditional way of writing is very inelegant, so today we introduce you to a more elegant way. HttpMessageConverter HttpMessageConverter is a message converter model provided by the Spring Framework, a policy interface for converting between HTTP requests

Spring Security's new JWT implementation

I have used the official spring-security-jwt provided by Spring as an implementation of JWT. This toolkit is no longer maintained. And it is not particularly compatible with the latest Spring Security OAuth2 Client and Spring Authorization Server. So I took two days to re-implement JWT with these two new dependencies. Nimbus Library The JOSE library nimbus-jose-jwt from Nimbus is used by default in the latest Spring Security. This library is currently one of the most used JOSE class libraries and most of the transformation work has been done around this library.

Spring Boot Rapid Integration with Swagger3

Interface documentation is always annoying, and I have tried using Postman to write and share project documentation, and it felt fine. But lately projects are tight and I don’t have extra time to spend on it, which led to my plan to try YApi (another kind of documentation) to go down the drain. Well, there is no faster and more foolproof tool than Swagger, although it has serious code pollution.

Verify the imported Excel data using jsr303

Recently in doing Excel import function, the product requires the imported data to be verified first and then into the library. So a simple package of tools, we think it’s not bad. Today, we will share the ideas. easyexcel library We all know that POI is the base library for Java manipulation of Excel. It is not customized for generality and has some limitations. After some research it was decided

The difference between WebSecurity and HttpSecurity in Spring Security

The Nature of HttpSecurity Spring Security 5.4 has a new way of configuring HttpSecurity. 1 2 3 4 5 6 7 8 9 @Bean SecurityFilterChain filterChain(HttpSecurity http) throws Exception { return http .antMatcher("/**") .authorizeRequests(authorize -> authorize .anyRequest().authenticated() ) .build(); } In fact, you can know that HttpSecurity is used to build a filter SecurityFilterChain that contains a series of filter chains, and normally our configuration is based around building SecurityFilterChain.

Spring Security Unit Testing

Spring Security Test Environment To use Spring Security in your unit tests, you need to add spring-security-test to your Spring Boot project. 1 2 3 4 5 <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> This way the contextual configuration of the tests can be combined with Spring Security, and the next few tricks will teach you. Spring Security Testing All tests are done under Spring Boot Test, which is supported by the @SpringBootTest annotation.

Various ways of handling exceptions in Spring

Usually the unified exception handling we set up in Spring Boot can only handle exceptions thrown by the Controller. Some requests have exceptions before they reach the Controller, and these exceptions cannot be caught by unified exceptions, such as some exceptions in the Servlet container. Today I encountered one in my project development, which irritated me because it returned an error message format that could not be handled uniformly, and

Spring Boot Containerization via Docker

Recently the company’s application ready to containerize, because dozens of applications from testing to release is too much trouble, and also because of environmental factors lead to a variety of problems in the deployment. In order to maintain a consistent environment in development, testing, production, the introduction of container technology, first take the edge of the project to try, to gain experience. Today a brief summary of several common Docker

SpringBoot integration of lightweight logging system loki - 2

Last post was a simple introduction to the use of Loki logging platform, and today a simple study of how to use Loki in practice to monitor Spring Boot applications, specially shared to give you a deeper understanding of this new technology. Loki’s log collection practice In previous article we used Docker Compose to start Grafana, Loki, and Protail at the same time to monitor an application. And the architecture of the whole logging system.

SpringBoot integration of lightweight logging system loki - 1

The project is formalized, the logging system is indispensable. The majority of logging platforms recommended to build based on ELK, but ELK is relatively heavy, the architecture is too large, small and medium-sized projects are not very good to hold, I hope to find a simple, if you really can not find then use ELK. before the reserve some technical candidates library, looked through the fruit of a logging system

ResponseEntity Usage Tips

The ResponseEntity object is Spring’s wrapper around the request response. It inherits from the HttpEntity object and contains the Http response code (httpstatus), the response header (header), and the response body (body). A Spring MVC interface to get user information usually we return the entity directly (with @RestController). 1 2 3 4 5 6 @GetMapping("/user") public User userinfo() { User user = new User(); user.setUsername("felord.cn"); return user; } is equivalent

Spring Security gets the currently logged in user

In some scenarios we need to get who the current user is? If you are using Spring Secrity as a security framework you can get the current user by using the following means. SecurityContext Either in stateful Session mode or in the popular JWT mode you can use SecurityContext to get the current user. 1 2 Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); String currentPrincipalName = authentication.getName(); Of course, this approach is not rigorous enough, if the interface allows anonymous access is likely to return an anonymous user, and anonymous users can not be obtained directly through getName, so we need to optimize the above logic.

Realm in Keycloak

In the previous posts, I joined you for a cursory look at Keycloak. As I gradually learned more, I found that I entered a misunderstanding, originally I thought that the focus of Spring Security integration with Keycloak was on this aspect of Spring Security, in fact, I found that Keycloak has no room to work with several filters on Spring Security’s Adapter, perhaps it needs I think we need to understand Keycloak itself before we can have a breakthrough.