标题配置文件给基本数据类型赋值(Interger、String)
1、实体类
包:com.service
Employee.java
package com.service;
public class Employee {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
2、配置文件
包:com.service
beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<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">
<bean id="emp1" class="com.service.Employee">
<property name="id" value="1" />
<property name="name" value="王明" />
</bean>
</beans>
给变量赋值,需要用到标签,相当于类中创建对象。id属性的值为存储这个对象的变量名,class属性的值为要赋值的变量所在类的包路径。标签就是具体的为某一个变量赋值,name属性的值为实体类中的要赋值的变量,value属性就是要为变量赋的值(仅支持数据类型)。
上述操作如果写到类中,相当于:
Employee emp1 = new Employee();
emp1.setId(1);
emp1.setName("王明");
3、创建ApplicationContext上下文容器,通过单例类
包名:com.util
ApplicationUtil.java
package com.util;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ApplicationUtil {
private ApplicationUtil(){
}
private static ApplicationContext ac = null;
static {
ac = new ClassPathXmlApplicationContext("com/test/beans.xml");//参数是beans.xml的包路径
}
public static ApplicationContext getApplicationContext(){
return ac;
}
}
4、测试类
包名:com.test
Test.java
public class Test{
public static void mian(String[] args){
ApplicationContext ac = ApplicationUtil.getApplicationContext();
Employee employee = (Employee) ac.getBean("emp1");//里面的参数是配置文件中<bean>标签的id值
Systm.out.println("员工Id:" + employee.getId() + "员工姓名:" + employee.getName());
}
}