spring学习笔记(二)— 配置xml文件并获取第一个bean
首先在eclipse中创建一个项目并导入需要的jar包,jar包的下载请看我的前一篇博客。
导入jar包后先创建一个class
package com.beanlife;
public class Persion {
private String name;
public final String getName() {
return name;
}
public final void setName(String name) {
this.name = name;
}
public void sayHi() {
System.out.println("你好, 我是" + name);
}
}
接着在项目下创建一个新建一个xml文件,我项目中的是applicationContext.xml,文件名可以自己定义,这个文件就是spring的配置文件了,上面的一大段直接拷贝就行,关键的地方在bean这一个节点里。
bean节点:
- id: 是自己定义的名称
- class: 是代码中的类的全路径
property节点:
- name: 成员属性的名称
- value: 给该成员属性赋的值
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<bean id="persion" class="com.beanlife.Persion">
<property name="name" value="森头"/>
</bean>
</beans>
注意:在使用spring配置bean时,相应的类(如:persion)的相应成员(如:name)一定要有set方法(如:setName(String name)),并且set方法的方法名是固定的(set+成员名,并且成员名首字母大写),我们可以用eclipse自动生成set方法,在eclipse中按下shift+alt+s,在弹出菜单中点击 Generate Getters and Setters,然后按需要操作即可。
接下来再创建一个test类
package com.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.beanlife.Persion;
public class Test {
public static void main(String[] args) {
// 传统
Persion persion = new Persion();
persion.setName("森头");
persion.sayHi();
// spring
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
Persion persion2 = (Persion) ac.getBean("persion");
persion2.sayHi();
}
}
在代码中传统的获得对象的方法和使用spring获得对象的方法
其中new ClassPathXmlApplicationContext(“applicationContext.xml”);中xml配置文件的名称以自己定义的为准;ac.getBean(“persion”);中以xml配置文件中自己定义的id为准。最后我们看下运行结果。
可以看到程序正常运行了,当然,如果有不正确的地方欢迎指出。