Spring base

2016-10-15  本文已影响9人  薛云龙

springIOC定义:spring容器控制对象的创建,初始化,销毁(控制反转),容器控制程序之间的关系,把控件权交给了外部容器

**spring对象的创建 **
配置文件:

1.applicationContext.xml并放在classes文件目录下,即src目录下
<!-- 这里的bean指的是要放入spring容器的类的全名,
id表示等下我们要获取对象使使用的Id。--> 
<bean class="com.xyl.helloSpring" id="hello"></bean>

别名:

<!-- name:表示对应的bean的id值。 alias:通过这个名字也能找到该id对应的类-->
  <alias name="hello" alias="找到对象"/>

测试

public class testHelloSpring { 
@Test public void test1(){
 //启动spring容器 
ApplicationContext applicationContext=new 
ClassPathXmlApplicationContext("applicationContext.xml"); 
//得到helloSpring对象 helloSpring 
helloSpring=(helloSpring) applicationContext.getBean("hello"); 
//调用相应的方法 helloSpring.hello(); }}

spring对象的创建方式

根据默认构造函数创建对象:如上
根据静态工厂类创建对象 :
静态工厂类:
public class helloFactory { 
public static helloSpring getInstance(){ 
return new helloSpring(); }}
配置文件:
<!-- factory-method:指的是工厂方法 --> 
<bean class="com.xyl.helloFactory.helloFactory" 
id="helloFactory" factory-method="getInstance"></bean>
测试:
//启动spring容器 
ApplicationContext applicationContext=new 
ClassPathXmlApplicationContext("applicationContext.xml"); 
//得到对象,注意这里getBean的id:helloFactory,但是得到的对象却可以是helloSpring ,因为在配置文件中bean我们配置了上面出现的属性:factory-method,
然后spring容器就跟我们调用静态工厂方法那样,直接通过类名调用,然后获得对象 
helloSpring helloSpring=(helloSpring) applicationContext.getBean("helloFactory"); 
//调用方法 
helloSpring.hello();
根据实例工厂类创建对象 
上一篇 下一篇

猜你喜欢

热点阅读