DEV Community

eidher
eidher

Posted on • Updated on

Autowiring in Spring

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

Top comments (2)

Collapse
 
kriska profile image
Kristina Gocheva

What are the advantages of autowiring? Would you recommended annotation configuration against xml configuration?

Collapse
 
eidher profile image
eidher • Edited

Autowiring requires less code, reduces development time, and is cleaner. XML configuration is a cumbersome and outdated form of configuration.