多次使用@Autowired

Por*_*Que 5 java spring hibernate spring-mvc

我对春天很新,所以我可能会问愚蠢的问题,但无论如何......

我已经构建了Spring MVC 4.0应用程序.

我的设置是这样的:

控制器>>服务>> DAO

在控制器级别我使用大约4到5个不同的@Autowired变量

@Autowired
private ClientService clientService;
@Autowired
private CommentService commentService;
@Autowired
private SearchService searchService;
Run Code Online (Sandbox Code Playgroud)

在服务级别I Autowire还有几个DAO

@Autowired
SearchDAO searchDAO;

@Autowired
private ActivityDAO activityDAO;

@Autowired
private UserService userService;
Run Code Online (Sandbox Code Playgroud)

我有大约10个不同的控制器,其中大多数是我@Autowire相同的服务,所以我的问题是否可以?

是否可以@Autowire根据需要使用多次,或者会占用太多内存?它会对我的应用程序产生其他影响吗?

我使用Spring 4.0 + hibernate JPA

Bhu*_*ale 6

没有问题@Autowired

Autowired 在 Spring 上下文中查找 bean 并分配给变量。它只是引用 Service/Dao bean 的同一个对象。它不会创建重复项。

但是,将如此多的对象注入到一个类中就表明一个类做了很多事情。检查尽可能将类重构为多个类的可能性。