以问答形式来学习springIOC。
1.为什么要有IOC(why)?
1>.使对象的使用和创建相分离,方便修改和扩展。
2>.使程序员专注于业务逻辑,不用自己去管理对象。
3>.将对象放在spring容器中,有利于spring提供的其他功能的使用。
2.什么是IOC(what)?
即,控制反转。把对象的创建、初始化、销毁等工作交给spring容器来做。
3.怎样启动Spring容器?(spring配置文件为:applicationContext.xml)
ApplicationContext context=new classPathXmlApplicationContext("applicationContext.xml");
4.根据id取出Spring容器中的bean.
com.java.Hello类中:
public class Hello{
public void hello(){
System.out.println("hello java");
}
}
applicationContext.xml中:
<bean id="hello" class="com.java.Hello"></bean>
client:
Hello h=(Hello)context.getBean("hello");
5.实例化bean的方式。
1>.Spring容器中默认调用类的默认构造函数,创建对象。
2>.利用静态工厂模式创建对象。
com.java.Hello类中:
public class Hello{
public void hello(){
System.out.println("hello java");
}
}
com.java.HelloFactory类中:
public class HelloFactory{
public static Hello creatInstance(){
return new Hello();
}
}
applicationContext.xml:
<bean id="hello" class="com.java.Hello"></bean>
<bean id="hello1" class="com.java.HelloFactory" factory-method="creatInstance"></bean>
client:
ApplicationContext context=new classPathXmlApplicationContext("applicationContext.xml");
Hello h=(Hello)context.getBean("hello1");
h.hello();
6.别名
<bean id="hello" class="com.java.Hello"></bean>
<alias name="hello" alias="h1">
<alias name="hello" alias="h2">//h1|h2都是hello的别名
7.spring容器创建对象的时机
1>.启动spring容器时创建对象。(只要配置文件有错,一开始就可以发现)
2>.context.getBean();时创建对象(前提:lazy-init="true");
8.spring容器默认创建的对像是单例的。
可将单利的改为多例的,只需修改:
<bean id="hello" class="com.java.Hello" scope="prototype"></bean>
9.初始化和销毁
<bean id="hello" class="com.java.Hello" init-method="init" destroy-method="destory"></bean>
public class Hello{
public void hello(){
System.out.println("hello java");
}
public void init(){
System.out.println("init");
}
public void destroy(){
System.out.println("destroy");
}
init方法是在调用类的默认的构造之后执行的;destroy方法是在spring执行close()方法之前执行的。
}
就到这里明天见哦。