標籤:rgs 結果 依賴注入 err ret xmla 使用者 style color
在spring的設定檔增加
<context:component-scan base-package="com.jmu.ccjoin.service"/>
<context:annotation-config />
1 public interface UserService { 2 3 /** 4 * 根據ID擷取使用者資訊 5 * 6 * @param id 7 * @return 8 */ 9 void get(Long id);10 }
1 public interface BuyerService {2 3 void get();4 }
1 @Service2 public class BuyerServiceImpl implements BuyerService {3 4 @Override5 public void get() {6 System.out.println("buyer landing...");7 }8 9 }
1 @Service 2 public class UserServiceImpl implements UserService { 3 4 //沒有UserDao類型注入到spring容器成bean 5 // @Autowired 6 // private UserDao userDao; 7 8 @Autowired 9 private BuyerService buyerService;10 11 public void get(Long id) {12 buyerService.get();13 System.out.println("userServiceImpl run sucess!!");14 }15 }
1 public static void main(String[] args) { 2 3 ApplicationContext app = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); 4 UserController userController = (UserController) app.getBean("userController"); 5 userController.save(); 6 7 System.out.println("----------------------------------"); 8 9 UserServiceImpl userServiceImpl = (UserServiceImpl)app.getBean("userServiceImpl");10 userServiceImpl.get(1L);11 12 System.out.println("----------------------------------");13 //userServiceImpl有注入到Spring容器,而userService並未注入到spring容器14 UserService userService = (UserService)app.getBean("userServiceImpl");15 userService.get(1L);16 }
注意:userServiceImpl和userService的類型都是userService,而userService並未在spring註冊成bean,所以userService類型只能取到userServiceImpl
在使用@Autowired時,首先在容器中查詢對應類型的bean
如果查詢結果剛好為一個,就將該bean裝配給@Autowired指定的資料
如果查詢的結果不止一個,那麼@Autowired會根據名稱來尋找。
如果查詢的結果為空白,那麼會拋出異常。解決方案時,使用required=false
spring就會去自動掃描base-package對應的路徑或者該路徑的子包下面的java檔案,如果掃描到檔案中帶有@Service,@Component,@Repository,@Controller等這些註解的類,則把這些類註冊為bean
DI依賴注入:只需要依賴spring-context包,依賴注入的是介面的話,介面一定要有實現。
IOC控制反轉:本來交給調用方new的,現在交給spring建立,並注入到調用方,控制方發生了反轉。其實控制反轉和依賴注入講的是一回事兒。
AOP面向切面:其應用如動態代理--要執行的方法,交給spring代理執行,並在調用方法前後加入其它邏輯。
另外:
IOC能夠被分解為兩種子類型:依賴注入和依賴尋找。
(1) 依賴尋找
比如使用 JNDI 註冊一個資料庫連接池的樣本中,代碼中從註冊處獲得依賴關係的 JNDI 尋找 (JNDI lookups):
CODE:
initContext = new InitialContext();
// 擷取資料來源
DataSource ds = (DataSource)initContext.lookup("java:comp/env/jdbc/mysql");
(2) 依賴注入
依賴注入的三種實作類別型:介面注入、 Setter 注入和構造器注入。
spring的依賴注入(DI)、控制反轉(IOC)和面向切面(AOP)