injection

 

Java依赖注入设计原则允许我们移除硬编码依赖和让我们的应用低耦合,可扩展和可维护。我们可以通过在Java中实现依赖注入将依赖关系从编译时移到运行时来解析。 Java依赖注入似乎很难通过理论来掌握。所以我将通过一些简单的例子,然后我们将会看到如何在应用里使用依赖注入模式来实现低耦合和可扩展性。

一个最好的setter依赖注入的例子是 Struts2 Servlet API Aware interfaces 到底是使用基于构造器依赖注入还是基于setter方法依赖注入取决于你的需求。举个例子,如果没有服务类我的应用完全不能运行,那么我会偏向基于构造器的DI,否则我会选择基于setter方法的DI,只有在真正需要才会使用它。 Java中的依赖注入是一种通过使对象从编译时绑定移到运行时绑定来实现控制反转(Inversion of control IoC)的一种方式。我们可以通过工厂模式(Factory Pattern), 模板方法设计模式(Template Method Design Pattern), 策略模式(Strategy Pattern)还有服务定位模式(Service Locator pattern)来实现IoC。 Spring依赖注入,Google Guice还有Java EE CDI框架通过使用Java Reflection API和Java注解来促进依赖注入的过程。我们只需要注解该域,构造器或者setter方法然后在配置xml文件或者配置类中配置它们。

Java依赖注入的好处 一些使用Java依赖注入的好处如下:关注点分离 应用程序类中的样板代码减少,因为所有用于初始化依赖性的工作都由注入器组件处理 配置组件使应用程序易扩展 通过模拟对象来单元测试会很简单 Java依赖注入的缺点

Java依赖注入也有一些缺点: 如果过度使用,可能会导致维护问题,因为更改的影响只有在运行时才知道。 Java中的依赖注入可能会隐藏导致运行时错误的服务类的依赖性,这会在编译时被捕获。 以上就是Java中的依赖注入模式。当我们控制服务时,了解和使用它是很好的。


转载于:https://www.cnblogs.com/zyhello/p/10482596.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Editorial Reviews Product Description Dependency Injection is an in-depth guide to the current best practices for using the Dependency Injection pattern-the key concept in Spring and the rapidly-growing Google Guice. It explores Dependency Injection, sometimes called Inversion of Control, in fine detail with numerous practical examples. Developers will learn to apply important techniques, focusing on their strengths and limitations, with a particular emphasis on pitfalls, corner-cases, and best practices. This book is written for developers and architects who want to understand Dependency Injection and successfully leverage popular DI technologies such as Spring, Google Guice, PicoContainer, and many others. The book explores many small examples of anchor concepts and unfolds a larger example to show the big picture. Written primarily from a Java point-of-view, this book is appropriate for any developer with a working knowledge of object-oriented programming in Java, Ruby, or C#. About the Author Dhanji R. Prasanna is an Enterprise Java consultant for technologies such as EJB3, JBI, JSF, Guice, Spring, HiveMind, and PicoContainer. He is a co-author of the Bean Validation (JSR-303), JAX-RS (JSR-311), Servlet 3.0 (JSR-315), and JavaServerFaces 2.0 (JSR-314) specifications. He is also co-author of the Java EE 6.0 (JSR-316) platform specification, which is the next edition of J2EE. Product Details * Paperback: 352 pages * Publisher: Manning Publications; 1 edition (August 28, 2009) * Language: English * ISBN-10: 193398855X * ISBN-13: 978-1933988559 * Product Dimensions: 9.1 x 7.4 x 0.8 inches
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值