봄의 자동 배선

생성자 주입




    @Autowired
    public AppServiceImpl(AppRepository appRepository) {
        this.appRepository = appRepository;
    }


메소드 주입




    @Autowired
    public setRepository(AppRepository appRepository) {
        this.appRepository = appRepository;
    }


필드 인젝션



권장하지 않습니다. 단위 테스트가 어렵습니다.

    @Autowired
    private AppRepository appRepository;


선택적 종속성



종속성이 있는 경우에만 주입:

    @Autowired(required=false)
    AppService appService;

    public void method() {
      if(appService != null) {
        ...
      }
    }


선택 사항 사용:

    @Autowired
    Optional<AppService> appService;

    public void method() {
      appService.ifPresent(s -> {
        ...
      });
    }


한정자 주석



구성 요소 이름을 지정하지 않으면 자동 생성됩니다. 지정되면 둘 이상의 빈 클래스가 동일한 인터페이스를 구현하는 경우 명확성을 허용합니다.

@Component
public class AppServiceImpl implements AppService {
    @Autowired
    public AppServiceImpl(@Qualifier("jdbcRepository") AppRepository appRepository) {
        this.appRepository = appRepository;
    }
}

@Component("jdbcRepository")
public class JdbcRepositoryImpl implements AppRepository {
    ...
}

좋은 웹페이지 즐겨찾기