使用Spring的IOC容器

首先编写AppBean

public class AppBean {
	private String helloString;

	public String getHelloString() {
		return helloString;
	}

	public void setHelloString(String helloString) {
		this.helloString = helloString;
	}
	
}

再编写Spring Beans的配置文件

<?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="appBean" class="org.zy.spring01.AppBean">
	<property name="helloString" value="hello,Spring"></property>
</bean>
<alias name="appBean" alias="app"/>
</beans>

最后使用IOC容器来获取AppBean,并为其赋值

public class App 
{
    public static void main( String[] args )
    {
    	ApplicationContext context=new ClassPathXmlApplicationContext("application.xml");
    	AppBean appBean=(AppBean) context.getBean("app");
    	System.out.println(appBean.getHelloString());
    }
}

输出结果
在这里插入图片描述如何理解这个过程呢?
在这里插入图片描述如上图所示,Spring的IOC container 对用户的pojo进行配置,代替用户实例化pojo,使得用户在使用pojo时,只需要去取,而不需要去创建。
通过debug代码
在这里插入图片描述可以看出在执行ApplicationContext context=new ClassPathXmlApplicationContext(“application.xml”);这行代码时,context对象已经为我们创建好了appBean对象。我们在使用时只需要调用getBean方法就好了。
另外也可以看到
在这里插入图片描述spring中的别名变量是使用map数据结构来保存的。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值