IOC(控制反转)
思想:
-
容器创建对象,将它们装配到一起,配置它们并管理它们的完整生命周期;
-
Spring容器通过依赖注入来管理组成应用程序的组件;
-
容器通过读取提供的配置元数据(通过XML、java注解、java代码提供)来接收对象进行实例化,配置和组装的指令。
spring依赖注入
依赖注入:
-
不必创建对象,但必须描述如何创建它们;
-
您不是直接在代码中将组件和服务连接在一起,而是描述配置文件中那些组件需要那些服务,由IOC容器将它们装配在一起。
依赖注入的方式:
public hshuo(String name){
this.name = name;
}
<bean id ="hshuo" class = "com.hshuo">
<constructor-arg value = "message"> </constructor-arg>
</bean>
public class hshuo{
pricate int id;
public int getId(){
return id;
}
public void setId(int id){
this.id = id;
}
}
<bean id = "hshuo" class = "com.hshuo">
<property name = "id" value = "123456"> </property>
</bean>
-
静态工厂注入:通过静态工厂的方法获取自己需要的对象
//静态工厂
public class DaoFactory{
//获取所需要的方法
public static final FactoryDao getStaticFactoryDaoImpl(){
return new StaticFactoryDaoImpl();
}
}
//通过spring注入对象
public class SpringAction{
private FactoryDao staticFactoryDao;
public void setStaticFactoryDao(FactoryDao staticFactoryDao){
this.staticFactoryDao = staticFactoryDao;
}
}
<bean name = "springAction" class = "SpringAction">
//注入对象
<property name = "staticFactoryDao" ref = "staticFactoryDao">
</property>
</bean>
//配置从工厂类获取的方法
<bean name = "staticFactoryDao" class = "DaoFactory"
factory-method = "getStaticFactoryDaoImpl">
</bean>
-
实例工厂:获取对象的实例方法不是静态的、不属于DaoFactory类,所以需要多添加一个<bean></bean>
//实例工厂
public class DaoFactory{
//获取所需要的方法
public FactoryDao getFactoryDaoImpl(){
return new FactoryDaoImpl();
}
}
//通过spring注入对象
public class SpringAction{
private FactoryDao FactoryDao;
public void setFactoryDao(FactoryDao FactoryDao){
this.FactoryDao = FactoryDao;
}
}
<bean name = "springAction" class = "SpringAction">
//注入对象
<property name = "FactoryDao" ref = "FactoryDao">
</property>
</bean>
//配置从工厂类获取的方法、
<bean name = "daoFactory" class = "com.DaoFactory"></bean>
<bean name = "factoryDao" factory-bean = "daoFactory"
factory-method = "getFactoryDaoImpl">
</bean>
参考链接: