In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article introduces to you what are the ten common mistakes made by Spring. The content is very detailed. Interested friends can use it for reference. I hope it will be helpful to you.
1. Mistake 1: pay too much attention to the bottom
We are solving this common mistake because the "not created by me" syndrome is very common in the field of software development.
Symptoms include frequent rewriting of common code, which is common to many developers. Although understanding the internal structure and implementation of a particular library is to a large extent good and necessary (it can also be a good learning process), as a software engineer, constantly dealing with the same underlying implementation details is harmful to a person's development career.
Abstract frameworks like Spring exist for a reason, freeing you from repetitive manual work and allowing you to focus on higher levels of detail-domain objects and business logic. Therefore, accept abstraction.
The next time you are faced with a specific problem, first do a quick search to determine whether the library that solves the problem has been integrated into Spring
Now, you may find a suitable ready-made solution. For example, a very useful library, in the rest of this article, I will use Project Lombok annotations in the examples. Lombok is used as a boilerplate code generator in the hope that lazy developers will not encounter problems when they are familiar with the library.
For example, take a look at what a "standard Java Bean" with Lombok looks like: as you might expect, the above code is compiled into: however, please note that if you plan to use Lombok in IDE, you will probably need to install a plug-in, which can be found here in the Intellij IDEA version.
2. Error 2: internal structure "leakage"
Exposing your internal structure is never a good idea because it creates inflexibility in service design and promotes bad coding practices. The internal mechanism of "disclosure" is to make the database structure accessible from some API endpoints.
For example, the following POJO ("Plain Old Java Object") class represents a table in the database:
Suppose there is an endpoint that needs to access TopTalentEntity data. It may be tempting to return an TopTalentEntity instance, but a more flexible solution is to create a new class to represent the TopTalentEntity data on the API endpoint.
In this way, making changes to the back end of the database will not require any additional changes at the service layer. Consider adding a "password" field to TopTalentEntity to store the Hash value of the user's password in the database-- if you don't have a connector like TopTalentData and forget to change the service front end, you will accidentally expose some unnecessary secret information.
3. Error 3: lack of separation of concerns
With the growth of program size, code organization has gradually become a more and more important issue. Ironically, most good software engineering principles begin to collapse on scale-especially if you don't think too much about program architecture.
One of the most common mistakes developers make is to confuse code concerns, which is easy to do! Often, the way to break the separation of concerns is to simply "pour" new functionality into existing classes. Of course, this is a good short-term solution (it requires less input for beginners), but it will inevitably become a problem in the future, whether during testing, maintenance, or somewhere in between.
Consider the following controller, which will return TopTalentData from the database.
Another advantage of this hierarchy is that it allows us to determine where the function resides by checking the class name. In addition, during testing, we can easily replace any class with a mock implementation if necessary.
Error 4: lack of exception handling or improper handling
Consistent themes are not unique to Spring (or Java), but they are still an important aspect to consider when dealing with Spring projects.
While coding styles can be controversial (usually agreed upon within the team or the entire company), having a common standard can ultimately greatly increase productivity. This is especially true for multiplayer teams; consistency allows communication to take place without spending a lot of resources on hand-to-hand handover or providing lengthy explanations for different types of responsibilities.
Consider a Spring project that contains various profiles, services, and controllers. By being semantically consistent in naming, you can create a structure that is easy to search, and any new developer can manage the code in his own way; for example, add a Config suffix to the configuration class, the service layer ends in Service, and the controller ends in Controller.
Closely related to the topic of consistency, server-side error handling deserves special emphasis. If you've ever had to deal with poorly written API exception responses, you probably know why-- parsing exceptions correctly can be painful, and determining why they happened in the first place is even more painful.
As an API developer, ideally you want to cover all user-facing endpoints and convert them to common error formats. This usually means having a common error code and description, rather than avoiding solving the problem: a) return a "500 Internal Server Error" message. B) return the stack information of the exception directly to the user.
In fact, this should be avoided at all costs, because in addition to being difficult for the client to handle, it also exposes your internal information. For example, a common error response format might look like this:
However, the above method (except for poor construction) is not a really "clean" solution. We are checking for validity of more than one type (that is, TopTalentData must not be empty, TopTalentData.name must not be empty, and TopTalentData.name is 10 characters long), and throw an exception if the data is invalid.
By integrating Hibernate validator into Spring, data validation can be done more cleanly. Let's first ReFactor the addTopTalent method to support validation:
7. Error 7: (still) use xml-based configuration
Although previous versions of Spring required XML, most of today's configuration can be done through Java code or annotations; XML configuration is just additional unnecessary boilerplate code. This article (and its accompanying GitHub repository) uses annotations to configure Spring,Spring to know which Bean to connect to, because the top-level package directory to be scanned has been declared in the @ SpringBootApplication compound annotation, as shown below:
Suppose you don't want to accidentally take any action on the production database when you modify the code, so it makes sense to set the default configuration file to dev.
Then, on the server, you can manually overwrite the configuration file by providing the-Dspring.profiles.active=prod parameter to JVM. In addition, the environment variable of the operating system can be set to the desired default profile.
9. Error 9: dependency injection cannot be accepted
Using Spring's dependency injection correctly means allowing it to connect all objects together by scanning all the necessary configuration classes; this is useful for decoupling relationships and makes testing easier, rather than doing so through tight coupling between classes:
Misko Hevery's Google talk provides an in-depth explanation of the "why" of dependency injection, so let's look at how it is used in practice.
In the section on separation of concerns (common error # 3), we created a service and controller class. Suppose we want to test the controller on the premise that TopTalentService behaves correctly. We can insert a mock object instead of the actual service implementation by providing a separate configuration class:
After that, we can inject Bean into the unit test using context configuration.
10. Error 10: lack of testing, or improper testing
Although the concept of unit testing has been around for a long time, many developers seem to either "forget" to do it (especially if it is not "necessary") or just add it afterwards.
This is obviously not desirable because tests should not only verify the correctness of the code, but also serve as documentation of how the program should behave in different scenarios. When testing Web services, only "pure" unit tests are rarely done, because communicating over HTTP usually involves calling Spring's DispatcherServlet and seeing what happens when an actual HttpServletRequest is received (making it an "integration" test, handling validation, serialization, and so on).
REST Assured, a Java DSL for simplifying testing of REST services, has been shown to provide a very elegant solution on top of MockMVC. Consider the following code snippet with dependency injection
The SampleUnitTestConfig class connects the mock implementation of TopTalentService to TopTalentController, while all other classes are standard configurations inferred by scanning the subordinate package directory of the package where the application class resides. RestAssuredMockMvc is simply used to set up a lightweight environment and send an GET request to the / toptal/get endpoint.
This is the end of the ten common mistakes made by Spring. I hope the above content can be helpful to you and learn more. If you think the article is good, you can share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.