Autowiring in Spring

eidher - Oct 5 '20 - - Dev Community

Constructor Injection

    @Autowired
    public AppServiceImpl(AppRepository appRepository) {
        this.appRepository = appRepository;
    }
Enter fullscreen mode Exit fullscreen mode

Method Injection

    @Autowired
    public setRepository(AppRepository appRepository) {
        this.appRepository = appRepository;
    }
Enter fullscreen mode Exit fullscreen mode

Field Injection

Not recommended. Hard to unit test.

    @Autowired
    private AppRepository appRepository;
Enter fullscreen mode Exit fullscreen mode

Optional dependencies

Only inject if dependency exists:

    @Autowired(required=false)
    AppService appService;

    public void method() {
      if(appService != null) {
        ...
      }
    }
Enter fullscreen mode Exit fullscreen mode

Using Optional:

    @Autowired
    Optional<AppService> appService;

    public void method() {
      appService.ifPresent(s -> {
        ...
      });
    }
Enter fullscreen mode Exit fullscreen mode

Qualifier Annotation

When component names are not specified, they are auto-generated. When specified, they allow disambiguation if more than one bean class implements the same interface.

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

@Component("jdbcRepository")
public class JdbcRepositoryImpl implements AppRepository {
    ...
}
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player