起源
idea 自動注入Mapper有警告,而且又紅色錯誤提醒(編譯可以通過)
這很煩,不是嗎? 我受夠了,得想點辦法。idea會提示
Spring team recommends: "Always use constructor based dependency injection in your beans. Always use assertions for mandatory dependencies."
為毛Spring這樣推薦哇?(⊙o⊙)嗯,按照提示先修改為:
private final UserMapper userMapper;
@Autowired
public UserServiceImpl(UserMapper userMapper) {
this.userMapper = userMapper;
}
複製程式碼
此時仍然存在一個問題是idea提示
Could not autowire.
自動注入 bean, spring幫助我們完成了,但是同時Spring提供了一些註解來顯式的註明bean之間的引用關係,其中最為熟知的自然是@Controller
,@Service
,@Repository
,@Component
等。
這裡其實給UserMapper
介面加上@Repository
,@Component
就可以解決,那麼他們之間有什麼區別?
區別@Controller
,@Service
,@Repository
,@Component
在Stackoverfolw找到了同樣的問題,得票最高的給出了一個表
Annotation | Meaning |
---|---|
@Component | generic stereotype for any Spring-managed component |
@Repository | stereotype for persistence layer |
@Service | stereotype for service layer |
@Controller | stereotype for presentation layer (spring-mvc) |
也提出,使用@Service, @Controller, @Repository更好做切面,也有人給出總結:
@Service, @Controller, @Repository = {@Component + some more special functionality}
為什麼建議構造器注入
構造器注入與域注入 熱門文章 Why field injection is evil 給出總結:
Field injection:
- less code to write
- unsafe code
- more complicated to test
Constructor injection:
- safe code
- more code to write (see the hint to Lombok)
- easy to test
Spring 的部落格上指出 Setter injection versus constructor injection and the use of @Required