@Autowired, @Qualifier, @Resource

@Autowired

@Autowired is used to inject objects into other objects, Spring provided

  1. no,
  2. byName,
  3. byType,
  4. constructor,
  5. autodetect. 

@Autowired on the properties: By default it takes “byType

We have SavingAccount.java, this service implemented by AccountController.java by Injecting SavingAccount into AccountController using @Autowired.

@Service
@Slf4j
public class SavingAccount {
    public void accountType() {
        log.info("Saving Account");
    }
}
public class AccountController {
    @Autowired
    private AccountService accountService;
    void getAccount(){
        accountService.accountType();
    }
}

@Qualifier

@Qualifier annotation avoid ambiguity and inject the required bean.

We get the ambiguity when the injected Service implemented by two classes as show in the blow example.

public interface AccountService {
    void accountType();
}

 

AccountService is implemented by SavingAccount and CurrentAcoount classes.

@Service
@Slf4j
public class SavingAccount implements AccountService {
    @Override
    public void accountType() {
        log.info("Saving Account");
    }
}

 

@Service
@Slf4j
public class CurrentAccount implements AccountService {
    @Override
    public void accountType() {
        log.info("Current Account");
    }
}

Now We @Autowired and @Qualifier required Service in the AccountController

public class AccountController {
    @Autowired     @Qualifier("currentAccount")     private AccountService accountService;     void getAccount(){         accountService.accountType();     } } 

If we don’t use @Qualifier then we get the

Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'accountController': 

@Resource

Instated of using @Autowired and @Qualifier we can use @Resource to inject bean and avoid ambiguity

public class AccountController {
    @Resource(name = "currentAccount")     private AccountService accountService;     void getAccount(){         accountService.accountType();     } }

 We get the bean name dynamic from the properties file using @Resource

public class AccountController {
    @Resource(name = "${beanName}")     private AccountService accountService;     void getAccount(){         accountService.accountType();     } }

In the properties file, we can mention as below

beanName = currentAccount

 

No comments:

Post a Comment