Spring自动装配Bean实现hello

通过xml配置自动装配Bean
1.创建一个简单的类test,作为被调用的Spring Bean。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package cn.zhenta.www.service.impl;

public class test
{
private String sex;

public void setSex(String sex) {
this.sex = sex;
}

public void pri(){
System.out.println("hi " + sex);
}
}

其中test类有一个sex的成员属性,两个方法(至于为什么有个setSex的方法,在第三点进行解释)。我们要实现的是另一个类通过xml自动装配这个类(Bean),来调用这个类的pri方法。所以我们再创建一个test1类,作为执行者。

2.创建执行的类test1,进行调用test的pri方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
package cn.zhenta.www.service.impl;

import org.apache.xbean.spring.context.ClassPathXmlApplicationContext;
import org.springframework.context.ApplicationContext;

public class test1 {

public static void main(String[] args) {
ApplicationContext a = new ClassPathXmlApplicationContext("test.xml");
test obj = (test) a.getBean("helloBean");
obj.pri();
}
}

被调用的类test和调用的类test1都创建好了,其中test.xml对应的是xml配置文件名称,helloBean对应的是test.xml配置文件中Bean的id,pri()即为test的pri方法,仅仅通过这两句话就可以不用实例化test类,即可调用test类的方法,怎么做到的呢?这就需要用到我们Spring的自动装配了,首先需要配置xml文件。

3.创建text.xml配置文件

1
2
3
4
5
6
7
8
9
10
<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-3.0.xsd">

<bean id="helloBean" class="cn.zhenta.www.service.impl.test">
<property name="sex" value="xsx" />
</bean>

</beans>

配置文件写好了,那配置文件里面的内容是什么意思呢?让我们慢慢道来,首先声明这是个Bean,然后class即为你要配置为Bean的类的命名空间(我这里对应的是第1点的test类),id即为表示你这个Bean的标识符(自己随意起名,不冲突即可),而property作为bean的属性,也就是指一个类中的成员,既name=“sex”对应test的sex成员变量,同时这个成员必须有get和set方法(既test类中的setSex()方法,需要注意的是setXXX的XXX需要为成员变量的名字),至于为什么要有set,get方法,可以阅读Spring IOC相关知识,至于property的用法,以下列举出一些常用的。

property的一般用法:

1
2
3
<bean id="playerDataManager" class="com.cp.game.PlayerDataManager" init-method="init" scope="singleton">

<property name="sleepTime" value="${app.dispatcher.sleepTime}" />

//从外部的property文件中用el表达式获取值

<property name="sleepTime" value="333" /> //直接在赋值

<property name="playerDao" ref="playerDao" /> 引用其他bean对象。 ref的值是其他bean的id名

4.运行结果
运行test1后,输出的内容是:hi xsx。

5.补充
两个Bean,person 和 ability。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.yiibai.common;

public class Person
{
private Ability ability;
//...
}
package com.yiibai.common;

public class Ability
{
private String skill;
//...
}

通过装配 hre装配

1
2
3
4
5
6
7
8
9
10
11
12
<bean id="person" class="com.yiibai.common.Person">
<property name="ability" ref="invisible" />
</bean>

<bean id="invisible" class="com.yiibai.common.Ability" >
<property name="skill" value="Invisible" />
</bean>
```
输出:

Person [ability=Ability [skill=Invisible]]
注意:想要自动装载,需要获Spring的上下文!

ApplicationContext a = new ClassPathXmlApplicationContext(“test.xml”);
test obj = (test) a.getBean(“helloBean”);
`

下一篇更新使用注解自动装载的时候,就不需要使用代码来获取了。欢迎加入JAVA学习群949419296,一起交流!