Day5——通过spring获取Bean对象

一. 回顾

前面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);
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值