Interpretation of Spring Boot the most popular 16 practice! [Share] Huawei Cloud

Sticky: Huawei cloud 618 big promotion hot in audience a fold, smoke free host, consumer full capacity to send P30 Pro, Click here to buy .

 

Spring Boot is the most popular Java framework for the development of micro-services. In this article, I will share best practices for using Spring Boot employed since 2016 in professional development. The content is based on articles Spring Boot expert and author of some well-known personal experience.

In this article, we will focus on Spring Boot specific practices (most of the time, also applies to the Spring project). The following are listed in order of best practices, in alphabetical order.

1, use custom BOM to rely on third-party maintenance

This practice is I summed up according to the actual project experience.

Spring Boot project itself uses and integrates a large number of open source projects, it helps us maintain these third-party dependencies. But there are also a part of and not included in the actual project use, which we need to maintain their own version of the project. If a large-scale projects, including a number of undeveloped module, so maintenance is very cumbersome.

How to do it? In fact, Spring IO Platform is to do this thing, which is itself Boot Spring subprojects, while maintaining other third party open source libraries. We can learn from the Spring IO Platform to write their own infrastructure projects platform-bom, all business modules project should be introduced as BOM. Such dependence upon third-party upgrades, you only need to upgrade this version of a dependent only.

2, the use of automatic configuration

A key feature is the use of Spring Boot autoconfiguration. This is part of the Spring Boot, it can simplify your code and make it work. When detecting a particular jar files on the classpath, automatic configuration is activated.

The easiest way to use it is dependent Spring Boot Starters. So, if you want to integrate with Redis, you can first include:

If you want to integrate with MongoDB, need:

With these starters, these tedious configuration can be well integrated together and work together, and they have been tested and verified. This is very helpful to avoid the dreaded Jar hell.

https://dzone.com/articles/what-is-jar-hell

By using the following annotation properties, some may be excluded from the auto-configuration class configuration:

But only when absolutely necessary should be done.

Official documents about the auto-configuration can be found here:

https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-auto-configuration.html

3, using Spring Initializr to start a new project Spring Boot

This is a best practice from Josh Long (Spring Advocate, @ starbuxman).

Spring Initializr provides a super simple way to create a new Spring Boot project and are likely to use to load dependency according to your needs.

https://start.spring.io/

Use Initializr create an application dependencies to ensure you get tested and validated, these dependencies automatically apply to Spring configuration. You may even find some new integration, but you may not be aware of these.

4, consider creating your own auto-configuration is a common organizational issues

This one also came from Josh Long (Spring Advocate, @ starbuxman) - This practice is for advanced users.

If you are a heavy reliance on Spring Boot company or team work, and have a common problem to be solved, then you can create your own automatic configuration.

This task involves more work, so you need to consider when benefits are worth the investment. Compared with the more than slightly different custom configuration, maintaining a single auto-configuration easier.

If this offer Spring Boot configuration is announced in open source libraries, it will simplify the configuration of thousands of users work greatly.

5, the correct design code directory structure

Despite allows you to have a lot of freedom, but there are some basic rules worth following to design your source code structure.

Avoid using the default package. Ensure that all content (including your entry points) are in the name of a good package, so you can avoid associated with the assembly and component scans of unforeseen circumstances;

The Application.java The (inlet type applications) remains in the top-level directory of the source;

I propose to put the controller module and service function-oriented, but this is optional. Some very good developers recommend that all controllers together. In any case, adhere to a style!

6, simple and focus on keeping @Controller

Controller should be very simple. You can read a description of the GRASP Controller pattern related parts here. You want the controller's role as coordinator and delegated, rather than performing the actual business logic. The following are major practices:

https://en.wikipedia.org/wiki/GRASP(object-orienteddesign)#Controller
  • The controller should be stateless! By default, the controller is a single embodiment, any state and may cause a number of problems;
  • The controller should not perform the business logic, instead rely commissioned;
  • The controller should handle HTTP application layer, which should not be transmitted to the service;
  • The controller should use cases / operational capacity to design around.

To further this content, the need for further understanding of the REST API design best practices. Whether you want to use Spring Boot, it is worth learning.

7, building around business functions @Service

Service is another core concept of Spring Boot. I found the best around business functions / areas / services to build the use case (no matter how you call will do).

Similar in design application name AccountService, UserService, PaymentServicesuch services, compared to like DatabaseService, ValidationService, CalculationServicethis would be more appropriate.

You can decide to use one to one mapping between Controler and Service, it would be the ideal situation. But this does not mean that you can not call each other Service!

8, so that independent of the database outside the core business logic

I had not yet determined how best to handle the database interaction in Spring Boot. After reading Robert · C · Martin's "Clear Architecture", for me it is much clearer.

You want your database logic separated from the service. Ideally, you do not want the service to know what it is to communicate with the database, which requires persistence to encapsulate some abstract objects.

Robert C. Martin strongly about how your database is a "detail", which means not to your particular application and database coupling. Over the past few people will switch databases, I noticed that the use of modern micro Spring Boot and service development make things faster.

9, from the business logic Spring Effect holding Boot Code

Taking into account the lessons "Clear Architecture", you should also protect your business logic. Various Spring Boot code is mixed together is very tempting ...... do not do. If you can resist the temptation, you will keep your business logic can be reused.

Some of the services usually become library. If you do not delete a large number of Spring comment from the code is easier to create.

10, recommended constructor injection

This is a practice from Phil Webb (Spring Boot project leader, @phillip_webb).

A method for holding the business logic from the code Spring Boot intrusion using constructor injection. Not only because @Autowiredannotation on the constructor is optional and can easily instantiate the bean in the absence of Spring.

11, are familiar with concurrency model

One of the most popular articles I've written is "Spring Boot introduction of concurrency." I think the reason for this is that this area is often misunderstood and overlooked. If used improperly, there will be problems.

https://www.e4developer.com/2018/03/30/introduction-to-concurrency-in-spring-boot/

In the Spring Boot, Controller and Service is the default is a single case. If you are not careful, it will be possible to introduce concurrency issues. You also typically limited processing thread pool. Please be familiar with these concepts.

If you are using the new WebFlux style Spring Boot application, I have explained it in "Spring's WebFlux / Reactor Parallelism and Backpressure" is how it works.

12, of strengthening the external configuration management

This is beyond the Spring Boot, although this is common when people began to create several similar service issues ......

You can be processed manually configure the Spring application. If you are dealing with multiple Spring Boot application, you need to make more powerful configuration management capabilities.

I recommend two main methods:

  • Using a configuration server, e.g. Spring Cloud Config;
  • All configuration is stored in an environment variable (it can be configured based on the git repository).

Any one of (the second option a little more) of these options require you to work less in DevOps, but in the field of micro service is very common.

13, a global exception handler

Do you really need abnormalities consistent method of processing. Spring Boot provides two main methods:

  • You should use HandlerExceptionResolver define a global strategy for exception handling;
  • You can also add @ExceptionHandler comment on the controller, which use may be useful in certain scenarios.

This is almost the same as in Spring and Baeldung have a detailed article on error handling REST and Spring's well worth a read.

https://www.baeldung.com/exception-handling-for-rest-with-spring

14, using the log frame

You probably already aware of this, but you should manually performed using Logger for logging, rather than using System.out.println (). This is easily done in Spring Boot, almost no configuration. Just get this kind of record instance:

This is important, because it allows you to set different logging levels as needed.

15, test your code

This is not unique to Spring Boot, but it need to be reminded - test your code! If you do not write tests, then you will start writing legacy code.

If other people use your code base, there will become dangerous to change anything. When you have more than one service interdependencies, which may even riskier.

Because of Spring Boot best practice, so you should consider for your Spring Cloud Contract consumer-driven contract, it will enable you to integrate with other services easier to use.

16, using the test sections to make testing easier and more focused

This is a practice from Madhura Bhave (Spring developers, @ madhurabhave23).

Use Spring Boot test code can be tricky - you need to initialize the data layer, a large number of service connections, simulate things ...... actually not that hard! The answer is to use the test sections.

Using a test slice, you can connect only part of the application as needed. This can save you a lot of time and make sure that your tests are not related to the content of unused Union. From http://spring.io article entitled Custom test slice with Spring test blog article 1.4 illustrates this technique.

https://spring.io/blog/2016/08/30/custom-test-slice-with-spring-boot-1-4

to sum up

Thanks Spring Boot, write Spring-based micro service is easier than ever. I hope that through these best practices, you will soon become not only the implementation process, but in the long run will be more powerful and successful.

Source: Hollis http://t.cn/EJWZNra Author: Bartosz Jedrzejewski

Contraband time: Huawei cloud 618 big promotion hot in audience a fold, smoke free host, consumer full capacity to send P30 Pro, Click here to buy .

Guess you like

Origin www.cnblogs.com/huaweicloud/p/11867824.html