spring依賴注入: 註解注入
註解注入顧名思義就是通過註解來實現注入,
Spring和注入相關的常見註解有Autowired、Resource、Qualifier、Service、Controller、Repository、Component。
[email protected]是自動注入,自動從spring的上下文找到合適的bean來注入
@Autowired(required=true)表示必須找到匹配的Bean,否則將報異常。
@Autowired預設按型別匹配注入Bean
在Spring中,@Autowired注入的型別可以是介面
比如,在Service層中注入Dao,如下示:
@Autowired private UserDao userDao;
[email protected]要求提供一個Bean名稱的屬性,如果屬性為空,自動採用標註處的變數名和方法名作為Bean的名稱 。
@Resource預設按名稱匹配注入Bean
比如,在Controller層中注入Service,名稱為Service的實現類,如下示
@Resource(name = "userServiceImpl") private UserService userService;
另外要注意,@Resource是java自帶的註解,不是Spring中的註解。@Resource註解完整的包路徑為import javax.annotation.Resource;
3.@Qualifier 指定注入bean的名稱
比如,在Controller層中注入Service,名稱為Service的實現類,如下示
@Autowired @Qualifier("userServiceImp") private UserSerevice userService;
[email protected],@Controller,@Repository分別標記類是Service層,Controller層,Dao層的類,spring掃描註解配置時,會標記這些類要生成bean。
@Repository用於標註資料訪問元件,即DAO元件
@Service,@Controller 這些註解要放在介面的實現類上,而不是介面上面。
[email protected]用於指定Bean的作用範圍
[email protected]和@Resource是用來修飾字段,建構函式,或者設定方法,並做注入的。
而@Service,@Controller,@Repository,@Component則是用來修飾類,標記這些類要生成bean。