beanをEmployee
beanのコンストラクタにautowiredしました。 Employee
beanのインスタンスを取得するときに、Address
のインスタンスを取得する必要があります。しかし、Springコンテナは、引数を持たないコンストラクタEmployee
を使用してインスタンスを返します。以下は、私のコードは、これは動作するはずSpringはBeanをロードするための自動構築コンストラクタを使用していません
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();
}
}
@Autowiredは「プライベートアドレスのアドレス」 –
に置かれるべき@FeiyuZhouが、私はコンストラクタでBeanを注入します。 –
no-argsコンストラクタを使用して新しいEmploye()を返す設定ファイルに@Beanアノテーションを使用してBeanを登録しているので、それは驚くべきことではありません。 – pzeszko