一. 回顾
前面Day2——搭建Spring环境讲到搭建spring环境,现在正式开始用spring获取Bean对象。
本篇文章讲述的项目源码:通过spring获取Bean对象项目源码
项目结构如下:
二. 步骤
如果还没有搭建好spring的环境,请查看Day2——搭建Spring环境
创建实体类:
Person.java
package com.atguigu.spring.bean;
/**
* Bean实体类
* @author user
*
*/
public class Person {
private String name;//姓名
private double salary;//工资
public Person() {
super();
// TODO Auto-generated constructor stub
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
@Override
public String toString() {
return "Person [name=" + name + ", salary=" + salary + "]";
}
}
在conf中创建Spring Bean Configuration File类型的applicationContext.xml文件。
applicationContext.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.xsd">
<bean id="person" class="com.atguigu.spring.bean.Person">
<property name="name" value="老王"></property>
<property name="salary" value="10000.00"></property>
</bean>
</beans>
Main.java
package com.atguigu.spring.bean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
/**
* 通过spring获取Bean对象
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//1. 首先获取IOC容器
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//2. 使用IOC容器获取Bean对象,通过id和class获取
Person person = context.getBean("person", Person.class);
//3.测试是否获取了person
System.out.println(person);
}
}