I have autowired Address
bean into the constructor of Employee
bean. And expect when getting instance of Employee
bean I should get an instance of Address
inside it. But Spring container is using no-args constructor of Employee
to return the instance. Below is my code
public class Address {
public void print(){
System.out.println("inside address");
}
}
public class Employee {
private Address address;
@Autowired
public Employee(Address address){
this.address = address;
}
public Employee(){}
public Address getAddress(){
return address;
}
}
@Configuration
@ComponentScan(basePackages={"com.spring"})
public class ApplicationConfig {
@Bean
public Employee employee(){
return new Employee();
}
@Bean
public Address address(){
return new Address();
}
}
public class Main {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfig.class);
Employee employee = (Employee)context.getBean("employee");
// Here add is null !!
Address add = employee.getAddress();
}
}