第五章 Spring4 自动装配、方法注入

Spring 自动装配:

通过配置 default-autowire 属性,Spring IOC 容器可以自动为程序注入 bean;默认是 no,不启用自动装配; default-autowire 的类型有 byName,byType,constructor;

byName:通过名称进行自动匹配;

byType:根据类型进行自动匹配;

constructor:和 byType 类似,只不过它是根据构造方法注入而言的,根据类型,自动注入;

建议:自动装配机制慎用,它屏蔽了装配细节,容易产生潜在的错误;


方法注入:

Springbean 作用域默认是 单例 singleton;

可以通过配置 prototype ,实现多例;

方法注入 lookup-method;



构造方法自动装配


<?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"
        default-autowire="constructor">

	<!-- 声明dog2,注入属性name -->
	<bean id="dog2" class="com.fx.entity.Dog">
		<property name="name" value="Jack"></property>
	</bean>
	
	
	<!-- 构造方法自动装配,将dog的值装配到people中 -->
	<bean id="people1" class="com.fx.entity.People">
		<property name="id" value="1"></property>
		<property name="name" value="张三"></property>
		<property name="age" value="11"></property>
	
	</bean>
	
</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">

	<!-- 声明实例dog -->
	<bean id="dog" class="com.fx.entity.Dog" scope="prototype">
		<property name="name" value="Jack"></property>
	</bean>
	
	
	<!-- 方法注入 -->
	<bean id="people1" class="com.fx.entity.People">
		<property name="id" value="1"></property>
		<property name="name" value="张三"></property>
		<property name="age" value="11"></property>
		<lookup-method name="getDog" bean="dog"/>
	</bean>
	
</beans>

猜你喜欢

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