Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using @Autowired many times

I'm very new to spring, so I might ask silly question but anyway...

I have built Spring MVC 4.0 application.

my settings are like this:

Controller >> Service >> DAO

in controller level I use about 4 to 5 different @Autowired variables like this

@Autowired
private ClientService clientService;
@Autowired
private CommentService commentService;
@Autowired
private SearchService searchService;

In Service level I Autowire also several DAOs

@Autowired
SearchDAO searchDAO;

@Autowired
private ActivityDAO activityDAO;

@Autowired
private UserService userService;

I have about 10 different controllers and in majority of them I @Autowire same services, So my question is this ok or not?

Is is ok to use @Autowire as many times as I need or will bring too much memory usage? Will it have some other effects on my application?

I use Spring 4.0 + hibernate JPA

like image 897
Por Que Avatar asked Mar 04 '16 18:03

Por Que


1 Answers

There is no problem with @Autowired.

Autowired finds the bean in Spring context and assign to the variable. It is just referencing to the same object of Service/Dao bean. It will not create duplicate.

But having so many objects injected to one class is a sign of one class doing a lot. Check possibility of refactoring the class into multiple classes wherever possible.

like image 189
Bhushan Bhangale Avatar answered Oct 07 '22 00:10

Bhushan Bhangale