Saturday, December 12, 2020

Dependency injection using Java Annotations

We can carry out dependency injection in Spring using Java annotations in three scenarios. 

  • Constructors
  • Setter functions
  • On Fields
We tell Spring to find an implementation for a dependency by using the @Autowired annotation. This will find an implementation of the dependency. If the dependency has several implementations, we'll get an error affecting all implementations. It's best to determine which implementation is appropriate by using the @Qualified annotation. 

@Autowired
@Qualified("randomFortuneService")
private FortuneService fortuneservice

remember when using default class implementation name of a dependency implementation, we use lowercase for the first letter. 

Furthermoer Bean Scope can also be defined using annotations

@Component
@Qualified("soccerCoach")
@Scope("prototype")
public class TennisCoach implements Coach {

No comments:

Post a Comment