您的位置:首页 > 编程语言 > Java开发

spring基础(一)

2015-09-10 14:21 477 查看
下面我们来讨论

1、spring IOC的定义

2、别名

3、spring对象的创建

4、spring对象的创建方式

springIOC的定义:

把创建对象的创建、初始化、销毁等工作交给spring容器来完成(控制反转)

构建开发环境:



单单做spring的话,可以直接只用上图中的2个jar包

那么,让spring容器来完成,首先就要把类写好,然后再把这个类放到spring容器里面,即放到spring的配置文件里面。

配置文件如下定义:

(a)名字一般为applicationContext.xml 并放在classes文件目录下,即src目录下。

(b)dtd约束为:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">[/code] 
(c)把写好的类放到配置文件中,

<!--
这里的bean指的是要放入spring容器的类的全名,id表示等下我们要获取对象使使用的Id。
-->
<bean class="cn.ansel.domain.helloSpring" id="hello"></bean>


别名:

就是可以使用其他名字来获得与该名字对应的对象

如果要使用别名的话,就在bean的下面多配置一行

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


对象的创建:

在创建好类及把类添加到配置文件之后,我们这里用一个测试类来调用一个类的方法:

类的代码如下:

public class helloSpring implements Serializable {

public void hello(){
System.out.println("hello spring!");
}
//构造函数
public helloSpring() {
System.out.println("new instance");
}
}


配置文件中的书写:

<bean class="cn.ansel.domain.helloSpring" id="hello"></bean>


测试类的书写:

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


运行之后的结果为:



从运行结果可以看到,spring调用了该类的默认构造函数来创建对象。

以上,就是spring创建对象的一种方法。

spring创建对象的方法

1、根据默认构造函数创建对象

2、根据静态工厂类创建对象

3、根据实例工厂类创建对象

在上面我们已经讨论了第一种。

现在我们来讨论第二种:根据静态工厂类创建对象

首先,我们一如既往的创建一个静态工厂类:

public class helloFactory {
public static helloSpring getInstance(){
return new helloSpring();
}

}


然后配置到配置文件中:

<!--
factory-method:指的是工厂方法
-->
<bean class="cn.ansel.helloFactory.helloFactory" id="helloFactory" factory-method="getInstance"></bean>


然后我们写一个测试类:

public class testFactory {
@Test
public void test(){
//启动spring容器
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
//得到对象,注意这里getBean的id:helloFactory,但是得到的对象却可以是helloSpring ,因为在配置文件中bean我们配置了上面出现的属性:factory-method,然后spring容器就跟我们调用静态工厂方法那样,直接通过类名调用,然后获得对象
helloSpring helloSpring=(helloSpring) applicationContext.getBean("helloFactory");
//调用方法
helloSpring.hello();
}
}


运行结果为:



3、根据实例工厂类创建对象

跟静态工厂差不多,只不过这里是利用实例工厂,所以在spring的配置文件的bean标签中还要添加一个属性:factory-bean:表示该类的实例

注意:判断一个spring容器中有多少个对象,就看其配置文件中有多少个bean,就算有factory-method/bean属性的,也算进去。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring 对象 ioc