Issue
I am learning Spring Boot and have quite a theoretical question. In this Udacity Example the model class is initiated manually:
ChatMessage newMessage = new ChatMessage();
Is it good practice?
I will elaborate further on this. Let's say I have a DateUtil class that does some date conversions, should I register it using @Component annotation or manage its dependency myself (DateUtil dateUtil = new DateUtil())?
So the main summarized question: How to know when to use component annotations and when to initialize classes manually?
Thanks a lot!!!
Solution
The answer to the first question is, yes, it's still okay, because beans are assumed to be singletones, although not always. In this case, it makes no sense to mark the ChatMessage class as a bean, since instances of this class will be created many times and it is absolutely unclear what benefit will be obtained if they are all beans and are located in the application context.
Answer to the second question: I think the DateUtil class should be instantiated in the usual way, because it looks like a regular utility class like StringUtils. Perhaps you should make its methods static and then you won't have to instantiate it at all. But if this is a complex class that contains business logic and / or is initialized with some data received from outside the application when it starts and this object of this class is used in other classes of the application, then it may be worth making it a bean.
The answer to the third question: it is difficult to give an unambiguous answer. Beans are worth creating when you want to achieve an inversion of control and not depend on the class you are injecting. Declaring a class as a component so that its instances become beans must make sense, bring an advantage to the design of the application.
You need experience with Spring applications to understand when to make beans. Take a look at some well-known Spring applications to understand in which case and which class instances are beaned.
Answered By - Андрей Колычев