spring 依赖注入的方式
构造器注入
public CatDaoImpl(String message){
this.message = message;
}
<bean id="catDaoImpl" class="com.CatDaoImpl">
<constructor-age value="message"></constructor-age>
</bean>
setter方法注入
public class Id{
private int id;
public int getId(){
return id;
}
public void setId(int id){
this.id = id;
}
}
<bean id="id" class="com.id">
<property name="id" value="123"></property>
</bean>
静态工厂注入
顾名思义,就是通过调用静态工厂的方法来获取自己需要的对象,为了让,spring管理所有对象,我们不能直接通过“工厂类.静态方法”来获取对象,而是依然通过spring注入的形式获取
//静态工厂
public class DaoFactory{
public static final FactoryDao getStaticFactoryDaoImpl(){
return new StaticFacotryDaoImpl();
}
}
public class SpringAction{
private FactoryDao staticFactoryDao; //注入对象
public void setStaticFactoryDao(FactoryDao staticFactoryDao){
this.staticFactoryDao = staticFactoryDao;
}
}
<!-- factory-method:指定使用哪个工厂方法 -->
<bean name="staticFactoryDao" class="com.DaoFactory"
factory-method="getStaticFactoryDaoImpl"></bean>
<bean name="springAction" class="com.SpringAction">
<property name="staticFactoryDao" ref="staticFactoryDao"></property>
</bean>
实例工厂
实例工厂的意思是获取对象实例的方法不是静态的,所以你需要首先new工厂类,再调用普通的实例方法
//实例工厂
public class DaoFactory{
public FactoryDao getFactoryDaoImpl(){
return new FactoryDaoImpl();
}
}
public class SpringAction{
private FactoryDao factoryDao;
public void setFactoryDao(FactoryDao factoryDao){
this.factoryDao = factoryDao;
}
}
<bean name="daoFactory" class="com.DaoFactory"></bean>
<bean name="factoryDao"
factory-bean="daoFactory"
factory-method="getFactoryDaoImpl"></bean>
<bean name="springAction" class="com.SpringAction">
<property name="factoryDao" ref="factoryDao"></property>
</bean>