Spring DI基础实例解析

1.        在程序中提供需要依赖Spring为其注入属性的属性名和类型

package com.hao947.ioc;

public class UserService {
	private String name;
	private String year;
	public void setName(String name) {
		this.name = name;
	}
	public void setYear(String year) {
		this.year = year;
	}
	public void show() {
		System.out.println("show...." + name + "," + year);
	}
}

2.        提供该属性的setter方法(标准封装的setter方法)

3.       spring中初始化该资源Bean时为其提供资源的值

<?xml version="1.0" encoding="UTF-8"?>
<!-- 整个Spring文件根元素就是beans -->
<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-3.1.xsd">
	<!-- 此处及用Bean元素来定义Spring能创建的对象 -->
	<bean id="userService" class="com.hao947.ioc.UserService">
		<!-- 为该Bean提供资源 -->
		<property name="name" value="hao947"></property>
		<property name="year" value="2014"></property>
	</bean>

</beans>

4.调试

public class IoCApp {
	@Test
	public void hao947() {
		// 获取Bean需要使用Spring的工厂类
		ApplicationContext act = new ClassPathXmlApplicationContext(
				"applicatioContext.xml");
		// 获取Bean
		UserService us = (UserService) act.getBean("userService");
		// 执行操作
		us.show();
		System.out.println(us);
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值