@Autowired註解注入map、list與@Qualifier
阿新 • • 發佈:2019-02-03
package com.imooc.beanannotation.multibean;
public interface BeanInterface {
}
package com.imooc.beanannotation.multibean;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Order(2)
@Component
public class BeanImplOne implements BeanInterface {
}
package com.imooc.beanannotation.multibean;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Order(1)
@Component
public class BeanImplTwo implements BeanInterface {
}
package com.imooc.beanannotation.multibean;
import java.util.List ;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
@Component
public class BeanInvoker {
@Autowired
private List<BeanInterface> list;
@Autowired
private Map<String, BeanInterface> map;
@Autowired
@Qualifier("beanImplTwo")
private BeanInterface beanInterface;
public void say() {
if (null != list && 0 != list.size()) {
System.out.println("list...");
for (BeanInterface bean : list) {
System.out.println(bean.getClass().getName());
}
} else {
System.out.println("List<BeanInterface> list is null !!!!!!!!!!");
}
System.out.println();
if (null != map && 0 != map.size()) {
System.out.println("map...");
for (Map.Entry<String, BeanInterface> entry : map.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue().getClass().getName());
}
} else {
System.out.println("Map<String, BeanInterface> map is null !!!!!!!!!!");
}
System.out.println();
if (null != beanInterface) {
System.out.println(beanInterface.getClass().getName());
} else {
System.out.println("beanInterface is null...");
}
}
}
@order 註解可以調整注入順序,但只對list有效,對map無效。
對於向map中注入,bean注入後string為該bean的id。
@Autowired
@Qualifier("beanImplTwo")
private BeanInterface beanInterface;
@Qualifier可以縮小範圍,指定注入物件的id
@request:這個屬性/方法必須複製,相當於@Autowired(request=true)