<beans>
<bean id="MovieLister" class="spring.MovieLister">
<property name="finder">
<ref local="MovieFinder"/>
</property>
</bean>
</beans>
3 接口:
public interface InjectFinder {
void injectFinder(MovieFinder finder);
}
class MovieLister implements InjectFinder
public void injectFinder(MovieFinder finder) {
this.finder = finder;
}
服务定位器
依赖注入最主要的好处是移除了MovieLister和MovieFinder的implementation(实现)上的依赖。但这并不是唯一的方法,另一种方法是服务定位器。
class ServiceLocator...
private static ServiceLocator soleInstance;
public static void load(ServiceLocator arg) {
soleInstance = arg;
}
private Map services = new HashMap();
public static Object getService(String key){
return soleInstance.services.get(key);
}
public void loadService (String key, Object service) {
services.put(key, service);
}
class Tester...
private void configure() {
ServiceLocator locator = new ServiceLocator();
locator.loadService("MovieFinder", new ColonMovieFinder("movies1.txt"));
ServiceLocator.load(locator);
}
class MovieLister...
MovieFinder finder = (MovieFinder) ServiceLocator.getService("MovieFinder");
依赖注入对于服务定位器来说是一种备选方案。服务定位器因为它的直接行为而有些许优势,但是如果你在很多应用中创建classes的时候,依赖注入是一种更好的选择。
思考:
1.Service Locator vs Dependency Injection
2.Constructor versus Setter Injection
3.Code or configuration files
4.Separating Configuration from Use
HashMap<String, Object> map= new HashMap<String, Object>();
//顶级菜单
List<DedeArctypes> toplist=testService.findDedeArctypes(topid,reid,typeid,"topid");
//二级菜单
for (DedeArctypes dedeArctypes1 : toplist) {
System.out.println("一级菜单"+dedeArctypes1.getTypename());
List<DedeArctypes> reidlist1=testService.findDedeArctypes(topid,dedeArctypes1.getId(),typeid,"reid");
map.put(dedeArctypes1.getId()+"", reidlist1);
for (DedeArctypes dedeArctypes2 : reidlist1) {
System.out.println("二级菜单"+dedeArctypes2.getTypename());
List<DedeArctypes> reidlist2=testService.findDedeArctypes(topid,dedeArctypes2.getId(),typeid,"reid");
map.put(dedeArctypes2.getId()+"", reidlist2);
for (DedeArctypes dedeArctypes3 : reidlist2) {
System.out.println("三级菜单"+dedeArctypes3.getTypename());
}
}
}