Reputation: 338
Is it good practice to set @Autowired fields in Spring to private for DI proposes?
I think it should be because nobody wants to access these fields directly outside of the class.
But on the other hand, Spring needs to access these. I know that it can do that also when they are private, but can it cause trouble? For example performance issues? (If I understand well in this case Spring uses Reflection, which can cause a small performance drop.) Or is this insignificant?
I googled and read tutorials for searching answers for this question, but I didn't find any "good" answers.
Which would be the best choice as an access modifier for these fields? Can you help me to understand this or indicate to me a resource where can I start to find an answer?
Upvotes: 0
Views: 6625
Reputation: 181
when you mark as autowired an object you're saying the container to handle that object's value, so you're just putting it as publicly accessible through the container. So it is already defined as public and singleton: this means that you could set as private the reference so that it won't be accessible outside the class, but its value will remain accessible through the container. If you want to set as private those variables do it, this won't hurt you, but obviously it is not a law because it will always depends on your needs. If you're looking at the performances be sure that private or public won't change nothing. Be sure to choose the right scope(singleton, prototype...), this will helps. If you need more informations read these questions:
How does @autowired annotation works for a private field?
How does Spring annotation @Autowired work?
why @autowired in spring does not need setter method for private instance variable?
Upvotes: 3