SpringIOC创建对象第一练

 

①创建IOC容器对象

package com.ioc.bean;

public class Book {
	
	private Integer BookId;
	private String BookName;
	private String author;
	private double price;
	
	
	
	public Book() {System.out.println("构造器已经创建");}
	
	
	
	public Book(Integer bookId, String bookName, String author, double price) {
		super();
		BookId = bookId;
		BookName = bookName;
		this.author = author;
		this.price = price;
	}



	public Integer getBookId() {
		return BookId;
	}
	public void setBookId(Integer bookId) {
		BookId = bookId;
	}
	public String getBookName() {
		return BookName;
	}
	public void setBookName(String bookName) {
		BookName = bookName;
	}
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	
	@Override
	public String toString() {
		return "Book [BookId=" + BookId + ", BookName=" + BookName + ", author=" + author + ", price=" + price + "]";
	}
	

}

ApplicationContext接口

package com.ioc.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

 public class IOCTest {

	@Test
	  public  void test() {
		ApplicationContext myIoc = new ClassPathXmlApplicationContext("j.xml");
		
		System.out.println("ioc已经创建");
		
		Object bean = myIoc.getBean("book01");
		
		System.out.println(bean);
	}

}


②调用IOC容器对象的getBean()方法即可获取IOC容器中配置的bean对应的对象

[1]getBean(String id) 根据配置文件中指定的bean的id获取

[2]getBean(Class<?> clazz) 根据bean的类型

根据类型获取bean的前提条件是IOC容器中指定类型的bean只有一个

<?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="book01" class="com.ioc.bean.Book">
		<property name="bookId" value="1"></property>
		<property name="bookName" value="bookName01"></property>
		<property name="author" value="author01"></property>
		<property name="price" value="100"/>
	</bean>
	

</beans>

 
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值