1.@Autowired
依賴注入的註解
2.@Primary
官網文檔的解釋:
對應的翻譯,來自搜狗(湊合可以看懂)
代碼示例:
個人理解:在通過javaconfig進行聲明bean時,加上該註解後,那個bean時首要選擇。
3.@Qualifier
標識符,因爲@Autowired默認時按照bean的類型注入(bytype),當別注入的接口有多個實現時,如果不加以區分,程序將會出現異常,使用@Qualifier進行標識來解決這個問題
示例:
聲明的bean
package com.lhj.service;
public interface UserService {
void eat();
}
-------------------------------------------------------------
package com.lhj.service.impl;
import com.lhj.service.UserService;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
public void eat() {
System.out.println("UserServiceImpl");
}
}
-------------------------------------------------------------
package com.lhj.service.impl;
import com.lhj.service.UserService;
import org.springframework.stereotype.Service;
@Service
public class UserServiceExtendImpl implements UserService {
public void eat() {
System.out.println("UserServiceExtendImpl");
}
}
注入並使用bean
package com.lhj.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Service
public class UserDemoService {
@Autowired
@Qualifier("userServiceExtendImpl")
private UserService userService;
}
添加@Qualifier來區分這裏的UserServiceImpl 和UserServiceExtendImpl 兩個bean ,@Qualifier括號內的值可以是bean的id或name值
官網文檔說明:
搜狗翻譯