IOC如何管理对象之间的依赖关系

IOC容器不是人类,无法像酒吧服务生一样通过大脑记忆对象之间的依赖关系。因而,它需要寻求其他方式记录对象的依赖关系 主流的IOC容器使用的注册对象管理信息方式有以下几种:

  1. 直接编码
  2. 配置文件方式
  3. 元数据方式

对于直接编码的方式

核心思路是:

为相应的类指定对应的具体实例,告知Ioc容器,当我们需要这种类型对象实例,把容器中注册的对应的具体实例返回。 其下是一段伪代码:
IoContainer container=....;
container.register(A.class,new  A());
	....
container.get(A.class)

当数据为接口注入的时候,多了一步接口注入的绑定过程,其下是伪代码,模拟其管理接口注入对象关系的过程:

IoContainer container=....;
container.register(A.class,new  A());
container.bind(B.class,container.get(A.class));
	....
container.get(B.class)

配置文件方式:

关系载体文件格式有普通文本文件 ,properties文件,xml文件等。最常见的是xml文件。 配置文件格式:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- services -->

    <bean id="petStore" class="org.springframework.samples.jpetstore.services.PetStoreServiceImpl">
        <property name="accountDao" ref="accountDao"/>
        <property name="itemDao" ref="itemDao"/>
        <!-- additional collaborators and configuration for this bean go here -->
    </bean>

    <!-- more bean definitions for services go here -->

</beans>

管理依赖关系:

container.readConfigurationFiles(....);
container.getBean(....);
	....

元数据方式(注解方式)

思路:以Goole Guice举例:

通过注解指明IOC通过什么方式注入。依赖注入的对象泽有Model提供

public class A{
	private ADao aDao;
	private BDao bDao;
	@Inject
	public A(ADao  aDao,BDao bDao ){
		this.aDao=aDao;
		this.bDao =bDao ;
	}
}
public class ModelA extends AbstractModel{
	@Override
	protected void configure(){
		bing(ADao .class).to(ADaoImpl.class).in(Scopes.SINGLETON);
		......
	}
}
经验分享 程序员 微信小程序 职场和发展