1. 程式人生 > >spring依賴註入

spring依賴註入

res 數據 ava context gap 名稱 tof 服務 ring

spring依賴註入:spring和註入相關的註解有:autoWired,resource,qualifier,service,controller,repository,component,

autoWired:自動從spring的上下文查找bean來註入。

resource:用來指定名稱來註入。

service,controller,repository用來註入服務層,控制層,數據庫層,spring掃描註解時,會標記這些需要生成bean。

上面的Autowired和Resource是用來修飾字段,構造函數,或者設置方法,並做註入的。而Service,Controller,Repository,Component則是用來修飾類,標記這些類要生成bean。

        ApplicationContext appContext = new AnnotationConfigApplicationContext("cn.outofmemory.helloannotation");
        CarService service = appContext.getBean(CarService.class);
        service.addCar("寶馬");

在上面的main方法中首先我們初始化了appContext,他是AnnotationConfigApplicationContext,它的構造函數接受一個package的名稱,來限定要掃描的package。

然後就可以通過appContext的getBean方法獲得CarService的實例了。

    <context:annotation-config />
    <context:component-scan base-package="cn.outofmemory.helloannotation" >
    </context:component-scan>





spring依賴註入