So basically two things to consider here. The 1st is that if a bean is required to be declared as a spring bean . It depends on if you need to use the spring features for this class such as @Transactional
, @Async
, @PreAuthorize
, @Autowired
(i.e dependency injection) , or ensure the bean has certain scope etc. If not , it is simpler not define it as a spring bean and simply create it by yourself.
So the following types of the classes are required to define them as spring bean in most cases:
- DAO because most probably need to inject
EntityManager
or JdbcTemplate
to it
- Controller because it is a part of spring-mvc and you need to define it as a bean such that you can use
@RequestMapping
/ @GetMapping
/ @PostMapping
/ @PutMapping
/ @DeletMapping
/ @PatchMapping
etc. on its method.
- Service class because you need to inject it into the controller and you need to use
@Transactional
to manage the DB transaction for its method.
For DTO , in most case you can create it by yourself since it is just a data container in nature and does not require to use any spring features.
The 2nd thing to consider is what scope does a bean should be. You mainly need to think about if an instance of that class is okay to be executed safely by multiple request (i.e thread) concurrently. If yes , you can simply use the default singleton scope. If not , you can think about if you want each HTTP request (i.e @RequestScope
) or each HTTP session (i.e. @SessionScope
) has their own instance of that class to work with. For example , if you are implementing some shopping cart , you most probably want that the HTTP session has their won instance of a shopping cart and so you should use @SessionScope
for the shopping cart.