SpringIOC容器-物件依賴

鬆門一枝花發表於2016-05-09

1 概述

Spring中,如何給物件的屬性賦值?  【DI, 依賴注入】
1) 通過建構函式
2) 通過set方法給屬性注入值
3) p名稱空間
4) 自動裝配
5) 註解


1.1 通過建構函式

<!-- ###############物件屬性賦值############### -->
	<!--  1) 通過建構函式 -->
	<bean id="user1" class="cn.itcast.c_property.User" scope="prototype">
		<constructor-arg value="100"></constructor-arg>
		<constructor-arg value="Tom"></constructor-arg>
	</bean>

1.2 (常用)Set方法注入值

<!-- dao instance -->
	<bean id="userDao" class="c_property.UserDao"></bean>

	<!-- service instance -->
	<bean id="userService" class="c_property.UserService">
		<property name="userDao" ref="userDao"></property>
	</bean>
	
	<!-- action instance -->
	<bean id="userAction" class="c_property.UserAction">
		<property name="userService" ref="userService"></property>
	</bean>


User.java

public class User {

	private int id;
	private String name;
	
	//////////////////  --> 通過容器注入屬性值
	public void setId(int id) {
		this.id = id;
	}
	// //--> 通過容器注入屬性值
	public void setName(String name) {
		this.name = name;
	}
	
	////////////////
	public int getId() {
		return id;
	}
	
	public String getName() {
		return name;
	}
	
	
	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + "]";
	}
	
	public User() {
		super();
		System.out.println("------User物件建立【無引數構造器】------");
	}
	
	public User(int id, String name) {
		System.out.println("-----User物件建立【帶引數構造器】--------");
		this.id = id;
		this.name = name;
	}

	public void init_user() {
		System.out.println("建立物件之後,初始化");
	}
	public void destroy_user() {
		System.out.println("IOC容器銷燬,user物件回收!");
	}
	
}

UserAction.java

public class UserAction {

	// Service: springIOC容器注入
	private UserService userService;
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	

	public String execute() {
		userService.save();
		return null;
	}
}

UserService.java

public class UserService {
	
	private UserDao userDao; // = new UserDao();
	// IOC:物件的建立交給spring的外部容器完成
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public void save() {
		userDao.save();
	}
}

UserDao.java

public class UserDao {

	public void save() {
		System.out.println("zmiagen:儲存使用者");
	}
}

1.3 內部bean

<!-- ##############內部bean############## -->
	<bean id="userAction" class="c_property.UserAction">
		<property name="userService">
			<bean class="c_property.UserService">
				<property name="userDao">
					<bean class="c_property.UserDao"></bean>
				</property>
			</bean>
		</property>
	</bean>



相關文章