首页 > 代码库 > Spring DI基础实例解析

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=http://www.mamicode.com/"hao947">>

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