Spring入门(二):IoC的使用——Bean装配

上文说到什么是Spring以及什么是IoC,这篇文章讲解如何使用IoC进行Bean的装配。
装配,即创建对象间的协作关系,也就是DI(依赖注入)。
在Spring中,我们通过IoC容器配置文件来完成依赖注入。
Spring框架为我们提供了一个IoC容器ApplicationContext(应用上下文)来管理Bean,ApplicationContext的构造方法参数为一个xml配置文件,接下来就以一个HelloWorld来进行说明。

package com.example.assembly;
//创建一个Bean
public class assemblytest {
	
	private String name;
	//编写Set方法用于传值注入
	public assemblytest(String name) {
		this.name = name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public void say() {
		System.out.println(name+" say:"+"Hello World"+this.hashCode());
	}
	
}
package com.example.assembly;

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

public class assemblyApplication {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//创建ApplicationContext
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("HelloConfig.xml");
		//通过ApplicationContext来获得Bean
		assemblytest test1 = (assemblytest)context.getBean("hello");
		assemblytest test2 = (assemblytest)context.getBean("hello");
		test1.say();
		test2.say();
		context.close();
	}

在这里插入图片描述
看上面这段代码,与不使用Ioc容器最大的不同就是我们取得对象不再通过New,而是通过ApplicationContext的getBean方法。为何我们能这样做,原因就是创建ApplicationContext对象时的参数——.xml的配置文件。
这个配置文件是这样写的:

<?xml version="1.0" encoding="UTF-8"?>
	<!--Spring 配置文件的模板-->
<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" >
		<!--配置assemblytest这个Bean -->
       <bean id="hello" class="com.example.assembly.assemblytest">
       		<property name="name" value="yuanran"/>
       </bean>
</beans>

通过配置文件我们实际上是告诉SpringIoC容器,将assemblytest这个类创建一个Bean(这里涉及Bean的作用域,以后讲解),它的Bean ID为"hello",所以我们能通过"hello"来获取这个类的实例。里面的property标签就对应assemblytest类的属性,value即初始化的值。到这里,一次简单的Bean装配就完成了。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值