[英]Spring IoC - Dependency Injection -> NullPointerException
[英]What is the point of XML IoC in Java Spring if dependency injection can be done without it?
我一直试图围绕 IoC 和依赖注入。 我想我开始了解大型应用程序中依赖注入的好处。 如果我的理解是正确的,当您拥有一致的接口时,依赖注入是有益的,因为您只能更改实现而无需更改整个应用程序。
我不明白 XML 是从哪里来的(而且我知道现在还有其他 IoC 方法,比如注释,但除非答案是“XML 很烂,你应该使用注释”,否则我们不要 go 那里)。
管理这个有什么区别:
public class MyApp {
public static void main(String[] args) {
ItemFinder theQuarterFinder = new QuarterItemFinder();
FortuneService theFortune = new HappyFortuneService(theQuarterFinder);
Coach theCoach = new WrestlingCoach(theFortune);
System.out.println(theCoach.getDailyWorkout());
System.out.println(theCoach.getDailyFortune());
System.out.println(theCoach.getItem());
}
}
并使用 xml 进行管理:
public class HelloSpringApp {
public static void main(String[] args) {
//Load spring configuration file
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");
//Retrieve bean from spring container
Coach theCoach = context.getBean("myCoach", Coach.class);
System.out.println(theCoach.getDailyWorkout());
System.out.println(theCoach.getDailyFortune());
System.out.println(theCoach.getItem());
context.close();
}
}
<bean id="myItemFinder" class="com.luv2code.springdemo.QuarterItemFinder">
</bean>
<bean id="myFortune"
class="com.luv2code.springdemo.HappyFortuneService">
<constructor-arg ref="myItemFinder" />
</bean>
<bean id="myCoach" class="com.luv2code.springdemo.WrestlingCoach">
<constructor-arg ref="myFortune" />
</bean>
如果我要更改 itemFinder 的实现,我将更改完全相同数量的代码,仅在 XML 文件与主应用程序 function 中进行。 这真的更可取吗? 试图追踪 XML 中的 refs 似乎比仅更改 MyApp 中的“新”调用之一更难处理。
如果我理解正确,这两个示例都进行了依赖注入。 只需将逻辑移出应用程序并放入 XML 文件中。 并创建 Spring Bean。 但是即使没有 XML 上下文,我们也有点在做豆子,对吗?
这是依赖注入原则、实践和模式的第12.2.1节的摘录,它解释了使用 (XML) 配置文件的优点和缺点。
12.2.1 使用配置文件配置容器
当 DI Containers 在 2000 年代初首次出现时,它们都使用 XML 作为配置机制——当时大多数事情都是这样做的。 使用 XML 作为配置机制的经验后来表明,这很少是最佳选择。
XML 往往冗长而脆弱。 当您在 XML 中配置 DI 容器时,您可以识别各种类和接口,但如果您拼错某些内容,则没有编译器支持来警告您。 即使 class 名称是正确的,也不能保证所需的程序集将位于应用程序的探测路径中。
雪上加霜的是,与纯代码相比,XML 的表达能力有限。 这有时使得在配置文件中表达某些配置变得困难或不可能,否则这些配置在代码中表达 [...]
另一方面,配置文件的优点是您可以更改应用程序的行为而无需重新编译。 如果您开发的软件交付给成千上万的客户,这是很有价值的,因为它为他们提供了一种定制应用程序的方法。 但是,如果您编写一个内部应用程序或一个您控制部署环境的网站,那么当您需要更改行为时,重新编译和重新部署应用程序通常会更容易。
总结:(XML)配置文件(仅)在后期绑定场景中有价值,其中类型在编译时未知,这很可能发生在允许使用插件扩展应用程序时。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.