[英]Spring does not use autowired constructor for loading the bean
我已經將Address
bean自動裝入Employee
bean的構造函數中。 並且期望在獲取Employee
bean的實例時,我應該在其中獲取Address
的實例。 但Spring容器使用Employee
no-args構造函數來返回實例。 以下是我的代碼
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();
}
}
正在使用no-arg構造函數,因為那是你正在調用的那個( new Employee()
):
@Bean
public Employee employee() {
return new Employee();
}
由於您是手動創建Employee
實例,而不是讓Spring為您創建它,您還必須自己傳遞Address
:
@Bean
public Employee employee() {
return new Employee(address());
}
請注意,對address()
多次調用實際上將返回相同的bean ,而不是多個新實例,如果這是你關注的話。
否則,替代方法是使用@Component
注釋Employee
,之后Spring將自動為您創建bean並連接到Address
依賴項。 您可以免費獲得該功能,因為您已打開組件掃描(假設Employee
位於您正在掃描的包中)。 如果你走這條路,你可以從配置類中刪除employee()
bean定義,否則最終可能會覆蓋另一個。
@Component public class Employee{ ... }
這應該工作。
如果您使用spring mvc項目,則必須在applicationContext.xml中啟用注釋,您必須添加此注釋<context:annotation-config>
然后您可以使用@Autowired ,如果您只使用spring Ioc,則只需在Employee上添加@Component和地址類
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.