我有一個用戶細節類裏面,我放置地址類來存儲每個用戶細節類的多地址。我正在使用Spring 4.0。下面給出的代碼:在春天用豆列表
的UserDetails類:
@Component("userDetails")
public class UserDetails {
@Resource(name="address")
@Autowired
private List<Address> address;
public List<Address> getAddress() {
return address;
}
@Autowired
public void setAddress(List<Address> address) {
this.address = address;
}
}
地址類:
@Component("address")
public class Address {
private String area;
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
}
在這個例子中,Address.area值需要在運行時通過,然後我需要創建地址類的對象。然後它需要添加UserDetails類中的List地址變量。同樣,我需要在arrayList中添加n個數字對象,然後我需要爲UserDetails類創建一個對象。
我嘗試下面的代碼:
public class AppMain {
public static void main(String args[]){
AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
Address address = (Address)context.getBean("address");
//setting first value:
address.setArea("XXX");
Address address1 = (Address)context.getBean("address");
//setting second value
address1.setArea("YYY");
UserDetails userDetails = (UserDetails)context.getBean("userDetails");
System.out.println("User Size: "+application.getAddress().size());
System.out.println("User Details : "+application.getAddress().get(0).getArea());
System.out.println("User Details : "+application.getAddress().get(1).getArea()); // getting ArrayIndexOutOfBoundException in this line
}
}
部分輸出: 用戶大小:1 用戶詳情:YYY
預期輸出: 用戶大小:2 用戶詳情:XXX 用戶詳情:YYY
您能否幫忙解決這個問題。
在運行時只有我來知道有多少地址塊將要創建。 – Praveen