we specify with @Autowired annotation the beans that will be injected in other beans using these annotation. @Autowired annotation can be applied on variables and methods for
autowiring byType. We can also use @Autowired annotation on constructor
for constructor based spring autowiring.
For @Autowired annotation to work, we also need to enable annotation
based configuration in spring bean configuration file. This can be done
by context:annotation-config element or by defining a bean of type
org.springframework.beans.factory.annotation.AutowiredAnnotation.
@Qualifier
annotation – This annotation is used to avoid
conflicts in bean mapping and we need to provide the bean name that will
be used for autowiring. This way we can avoid issues where multiple
beans are defined for same type. This annotation usually works with the
@Autowired annotation.
Autowire-candidate="false"
is used in a bean definition to
make it ineligible for autowiring. It’s useful when we have multiple
bean definitions for a single type and we want some of them not to be
autowired. For example, in above spring bean configurations “employee1”
bean will not be used for autowiring.
Spring @Autowired Annotation – autowiring byType Example
package com.
javaInterviewConcept
.spring.autowiring.service;
import org.springframework.beans.factory.annotation.Autowired;
import com.javaInterviewConcept.spring.autowiring.model.Employee;
public class EmployeeAutowiredByTypeService {
//Autowired annotation on variable/setters is equivalent to autowire="byType"
@Autowired
private Employee employee;
@Autowired
public void setEmployee(Employee emp){
this.employee=emp;
}
public Employee getEmployee(){
return this.employee;
}
}
Spring @Autowired Annotation and @Qualifier Bean autowiring by constructor Example
package com.
javaInterviewConcept
.spring.autowiring.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import com.
javaInterviewConcept
.spring.autowiring.model.Employee;
public class EmployeeAutowiredByConstructorService {
private Employee employee;
//Autowired annotation on Constructor is equivalent to autowire="constructor"
@Autowired(required=false)
public EmployeeAutowiredByConstructorService(@Qualifier("employee") Employee emp){
this.employee=emp;
}
public Employee getEmployee() {
return this.employee;
}
}
No comments:
Post a Comment