第三章 Spring4 依赖注入

第一节:装配一个 bean



第二节:依赖注入


IOC(控制反转:InverseofControl ) ,又称作 依赖注入,是一种重要的面向对象编程的法则来削减计算机程序 的耦合问题,也是轻量级的 Spring 框架的核心。

1,属性注入;

2,构造函数注入;(通过类型;通过索引;联合使用)

3,工厂方法注入;(非静态工厂,静态工厂)

4,泛型依赖注入;(Spring4 整合 Hibernate4 的时候顺带讲)



<?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="people" class="com.fx.entity.People"></bean>
	<!-- 属性注入 -->
	<bean id="people2" class="com.fx.entity.People">
		<property name="id" value="1"></property>
		<property name="name" value="张三"></property>
		<property name="age" value="11"></property>
	</bean>
	
	<!-- 构造方法注入 -->
	<bean id="people3" class="com.fx.entity.People">
		<constructor-arg type="int" value="2"></constructor-arg>
		<constructor-arg type="String" value="李四"></constructor-arg>
		<constructor-arg type="int" value="22"></constructor-arg>
	</bean>
	
	<bean id="people4" class="com.fx.entity.People">
		<constructor-arg index="0" value="3"></constructor-arg>
		<constructor-arg index="1" value="王五"></constructor-arg>
		<constructor-arg index="2" value="55"></constructor-arg>
	</bean>
	
	<bean id="people5" class="com.fx.entity.People">
		<constructor-arg index="0" type="int" value="4"></constructor-arg>
		<constructor-arg index="1" type="String" value="招六"></constructor-arg>
		<constructor-arg index="2" type="int" value="66"></constructor-arg>
	</bean>
	
	<bean id="peopleFactory" class="com.fx.factory.PeopleFactory"></bean>
	
	<!-- 工厂方法注入 -->
	<bean id="people7" factory-bean="peopleFactory" factory-method="createPeople"></bean>
  
  	<bean id="people8" class="com.fx.factory.PeopleFactory2" factory-method="createPeople"></bean>
</beans>

猜你喜欢

转载自1151461406.iteye.com/blog/2389894