DEV Community

eidher
eidher

Posted on • Edited on

3

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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

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.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay