1. 程式人生 > >spring學習筆記(13)——註解Autowired自動裝配

spring學習筆記(13)——註解Autowired自動裝配

使用Autowired

  • 一般情況下,controller和service是有關聯關係的,service和DAO層是有關聯關係的,我們使用autowired註解,在controller中裝配service,在service中裝配reponsitory
package com.zj.annotation.service;

public interface TestService {
    void add();
}
package com.zj.annotation.service;

import org.springframework.stereotype.Repository;
import
org.springframework.stereotype.Service; @Service public class TestServiceImpl implements TestService { @Override public void add() { System.out.println("service impl add....."); } }
@Controller
public class TestController {

    @Autowired
    private TestService testService;

    public
void excute(){ testService.add(); } }
  • 注意,使用autowired的前提是TestService的bean歸IOC容器管理(使用註解或配置檔案配置的方式配置了該bean)
  • 如果沒有建立testService這個bean,那麼將拋異常
  • 也可以使用required=false來宣告可以不建立該bean:@Autowired(required=false)
  • autowired也可以用於方法
@Controller
public class TestController {

    private
TestService testService; @Autowired private void getTestService(TestService testService) { this.testService = testService; } public void excute(){ testService.add(); } }

這種寫法和上面效果一樣

細節注意

  • 如果有多個類實現了TestService這個介面,那麼autowired會自動裝配哪個?

    根據實現類的name,如其中一個實現類:@Service(“testService”),那麼就自動裝配這個實現類,因為private TestService testService;

  • 如果有多個實現類,但是沒有指明name怎麼辦?

    如果沒有指明name,將會拋異常,但是我們可以使用@Qualifier註解來說明使用哪一個實現類

@Controller
public class TestController {

    @Autowired
    @Qualifier("testServiceImpl2")
    private TestService testService;

    public void excute(){
        testService.add();
    }
}

實現類為TestServiceImpl2,bean的name(id)預設為testServiceImpl2

  • @Qualifier也可以用於方法,或者方法的引數,如:
    private TestService testService;

    @Autowired
    @Qualifier("testServiceImpl2")
    private void getTestService(TestService testService) {
        this.testService = testService;
    }

或者

    private TestService testService;

    @Autowired
    private void getTestService(@Qualifier("testServiceImpl2")TestService testService) {
        this.testService = testService;
    }