A mostly reasonable approach to Spring Boot.
- Never use
field injection
orsetter injection
. Useconstructor injection
instead.
Why? See Why field injection is evil for an in-depth discussion.
// really bad
@AutoWired
private PersonRepository personRepositoy;
// still bad
private PersonRepository personRespository;
@Autowired
public void setPersonRepository(PersonRepository personRepository) {
this.personRepository = personRepository;
}
// good
private final PersonRepository personRepository;
public PersonService(PersonRepository personRepository) {
this.personRepository = personRepository;
}
- Use
@GetMapping
,@PostMapping
etc. instead of@RequestMapping
.
Why? They are easier to read and force you to declare the request method.
// bad
@RequestMapping(method = RequestMethod.GET, value = "/person/{id}")
public Person show(@PathVariable long id) {
}
// good
@GetMapping("/person/{id}")
public Person show(@PathVariable long id) {
}
// good
public class Person {
private final String firstname;
private final String lastname;
@JsonCreator
public Person(String firstname, String lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
public String getFirstname() {
return firstname;
}
public String getLastname() {
return lastname;
}
}