控制反转/依赖注入是两个影响广泛的设计模式,也是主流J2ee框架Spring的核心概念,
其主要目的就是为了管理对象之间的关系,为对象之间解除耦合,把对象生命周期的管理和关系的管理这些和对象个体无关的公共任务交给公共容器处理。
好比当你需要钟点工的时候,你把需求依赖告知服务公司,服务公司为你安排具体人员,而无需你自己操心。
当然任何设计模式有其优点就必有其缺点,我们需要理解其设计本意,才能在合适的场景下应用。
时间一长,概念就会模糊,下面的文章转自网络(删除了一些情绪化词句),方便自己查阅。
public class ImageReaderFactory { public static ImageReader getImageReader(InputStream is) { int imageType = determineImageType(is); switch(imageType) { case ImageReaderFactory.GIF: return new GifReader(is); case ImageReaderFactory.JPEG: return new JpegReader(is); ...// etc. } } }
public class ServiceLocator { private static ServiceLocator serviceLocatorRef = null; ... static { serviceLocatorRef = new ServiceLocator(); } private ServiceLocator() { ... } public static ServiceLocator getInstance() { return serviceLocatorRef; } public EJBHome getRemoteHome(String jndiHomeName, Class className) throws ServiceLocatorException { EJBHome home = null; ... return home; } }
<bean id="exampleBean" class="examples.ExampleBean"> <!-- constructor injection using the nested <ref/> element --> <constructor-arg> <ref bean="anotherExampleBean"/> </constructor-arg> <!-- constructor injection using the neater 'ref' attribute --> <constructor-arg ref="yetAnotherBean"/> <constructor-arg type="int" value="1"/> </bean> <bean id="anotherExampleBean" class="examples.AnotherBean"/> <bean id="yetAnotherBean" class="examples.YetAnotherBean"/> public class ExampleBean { private AnotherBean beanOne; private YetAnotherBean beanTwo; private int i; public ExampleBean(AnotherBean anotherBean, YetAnotherBean yetAnotherBean, int i) { this.beanOne = anotherBean; this.beanTwo = yetAnotherBean; this.i = i; } }
<bean id="exampleBean" class="examples.ExampleBean"> <!-- setter injection using the nested <ref/> element --> <property name="beanOne"> <ref bean="anotherExampleBean"/> </property> <!-- setter injection using the neater 'ref' attribute --> <property name="beanTwo" ref="yetAnotherBean"/> <property name="integerProperty" value="1"/> </bean> <bean id="anotherExampleBean" class="examples.AnotherBean"/> <bean id="yetAnotherBean" class="examples.YetAnotherBean"/> public class ExampleBean { private AnotherBean beanOne; private YetAnotherBean beanTwo; private int i; public void setBeanOne(AnotherBean beanOne) { this.beanOne = beanOne; } public void setBeanTwo(YetAnotherBean beanTwo) { this.beanTwo = beanTwo; } public void setIntegerProperty(int i) { this.i = i; } }
public class Student { private IBook book; public init() { book = (IBook)Class.forName(“Book”).newInstance(); } } public interface IBook { public void learn(); } public class Book implements IBook { public void learn() { …//etc } }
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
参考阅读:
http://en.wikipedia.org/wiki/Spring_Framework