1. Define profile information
Sometimes we put some variables in order to unify management yml In the configuration file
for example
use @ConfigurationProperties replace @Value
usage method
Define the entity of the corresponding field
@Data
// Specify prefix
@ConfigurationProperties(prefix = "developer")
@Component
public class DeveloperProperty {
private String name;
private String website;
private String qq;
private String phoneNumber;
}
@Data // Specify prefix @ConfigurationProperties(prefix = "developer") @Component public
class DeveloperProperty { private String name; private String website;
private String qq; private String phoneNumber; }
Inject this when using bean
@RestController @RequiredArgsConstructor public class PropertyController {
final DeveloperProperty developerProperty; @GetMapping("/property")
public Object index() { return developerProperty.getName(); } }
2. use @RequiredArgsConstructor replace @Autowired
We all know that injecting one bean There are three ways (set injection , Constructor Injection , Annotation injection ),Spring It is recommended that we use constructor injection Bean
Let's take a look at what the previous code looks like after compiling
RequiredArgsConstructor:lombok provide
3. Don't go back null
Counterexample
Positive example
When a method is called elsewhere , Avoid unnecessary null pointers
optional Air judgment
// Get subdirectory list public List<CatalogueTreeNode> getChild(String pid) {
if (V.isEmpty(pid)) { pid =
BasicDic.TEMPORARY_DIRECTORY_ROOT; } CatalogueTreeNode node =
treeNodeMap.get(pid); return Optional.ofNullable(node)
.map(CatalogueTreeNode::getChild)
.orElse(Collections.emptyList()); }
4. if else
Not too much if else if, You can try the strategy mode instead
5. reduce controller Business code
The business code should be placed as far as possible service Layer processing , It is easy to maintain and operate in the later stage, and it is beautiful
Counterexample
Positive example
Technology
Daily Recommendation