spring是一个开源的控制反转(IOC)和面向切面(AOP)的框架,它的主要目的是简化企业的开发。
IOC:
依赖注入:
SpringDi就是依赖注入,意思就是在运行期,由外部容器动态地将依赖对象注入到组件中。
Spring实例化Bean的方式:
1.是使用类构造器实例化(默认无参数:xml配置使用bean的类构造器):
<bean id="contextConf" class="com.koubei.util.ContextConf"/>
2.是使用静态工厂方法实例化(简单工厂模式:xml配置+factory类)
<bean id="contextConf" class="com.koubei.util.ContextConf" factory-method="createContext" />
例子:
(1).首先写工厂类.他其中包含产生我们的业务bean的方法
public class PersionServiceBeanFactory{
public static PersionServiceBean createPersionServiceBean() {
return new PersionServiceBean();
}
}
(2).改写beans.xml :包含工厂类类名和产生业务bean的方法名字
<bean id="persionServiceBean2" class="cn.com.xinli.service.impl.PersionServiceBeanFactory"factory-method="createPersionServiceBean"/>
(3)本地调用:
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
PersionSevice ps=(PersionSevice)ctx.getBean("persionServiceBean2");
ps.save();
3.使用实例工厂方法实例化:
<bean id="PersionServiceBeanFactory" class="cn.com.xinli.service.impl.PersionServiceBeanFactory"</bean>
<bean id="persionServiceBean3" factory-bean="PersionServiceBeanFactory" factory-method="createPersionServiceBean2"></bean>
例子:
package cn.com.xinli.service.impl;
public class PersionServiceBeanFactory{
public static PersionServiceBean createPersionService(){
return new PersionServiceBean();
}
public PersionServiceBean createPersionServiceBean2(){
return new PersionServiceBean();
}
}
(2)改写beans.xml :写两个bean,一个是工厂bean,一个是利用工厂bean产生业务bean的bean.
<bean id="PersionServiceBeanFactory" class="cn.com.xinli.service.impl.PersionServiceBeanFactory"></bean>
<bean id="persionServiceBean3" factory-bean="PersionServiceBeanFactory" factory-method="createPersionServiceBean2"></bean>
(3)本地测试
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
PersionSevice ps=(PersionSevice)ctx.getBean("persionServiceBean3");
ps.save()