`
lanqiaoyeyu
  • 浏览: 24397 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

Spring学习(四) 注入依赖对象

    博客分类:
  • Java
 
阅读更多
依赖注入(Dependency Injection)
所谓的依赖注入就是指:在运行期间,由外部容器动态地将依赖对象注入到组件中。
一、注入方式
1、通过构造方法注入
package com.bill.impl;
import com.bill.PersonService;
import com.bill.dao.PersonDao;
/**
 * @author Bill
 */
public class PersonServiceBean implements PersonService {
	private PersonDao personDao;
	private String name;
	
	public PersonServiceBean(PersonDao personDao, String name) {
		this.personDao = personDao;
		this.name = name;
	}
	public void save(){
		personDao.add();
		System.out.println(name);
	}	
}

	<bean id="personDao" class=" com.bill.dao.impl.PersonDaoBean"/>
	<bean id="personService" class="com.bill.impl.PersonServiceBean">
		<constructor-arg index="0" type="com.bill.dao.PersonDao" ref="personDao"></constructor-arg>
		<constructor-arg index="1" value="good"></constructor-arg>
	</bean>

测试代码:
		AbstractApplicationContext act = new ClassPathXmlApplicationContext("beans.xml");
		PersonService personService = (PersonService)act.getBean("personService");
		personService.save();
	    act.close();

2、通过属性setter方法注入
如二.1

3、使用注解方式注入
在java代码中使用@Autowired或者@Resource注解方式进行装配。这两个注解的区别是:@Autowired默认按类型装配,@Resource默认按名称装配,当找不到与名称匹配的bean才会按类型装配。需配置xml文件如下:
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd">
    <context:annotation-config/>
	<bean id="personDao" class=" com.bill.dao.impl.PersonDaoBean"></bean>
	<bean id="personService" class="com.bill.impl.PersonServiceBean"></bean>
</beans>

这种配置隐式注册了多个对注解解析处理的处理器AutowriedAnnotationBeanPostProcessor,CommonAnnotationBeanPostProcessor,PersistenceAnnotationBeanPostProcessor,RequiredAnnotationBeanPostProcessor

使用@Resource注解的业务代码如下:
1)标注在字段上的方式
package com.bill.impl;
import javax.annotation.Resource;

import com.bill.PersonService;
import com.bill.dao.PersonDao;
/**
 * @author Bill
 */
public class PersonServiceBean implements PersonService {
	@Resource private PersonDao personDao;
	//@Resource(name="personDao") private PersonDao personDao;//采用指定name属性的方式,寻找xml中指定的bean
	public void save(){
		personDao.add();
	}
}

2)标注在setter方法上的方式
package com.bill.impl;

import javax.annotation.Resource;
import com.bill.PersonService;
import com.bill.dao.PersonDao;
/**
 * @author Bill
 */
public class PersonServiceBean implements PersonService {
	private PersonDao personDao;

	@Resource
	public void setPersonDao(PersonDao personDao) {
		this.personDao = personDao;
	}


	public void save(){
		personDao.add();
	}
}

在@Resource中没有指定name属性时,Spring会根据该字段的名称personDao去xml中寻找匹配的bean,假如找不到,再去根据该字段的类型去寻找匹配的bean。

注意:@Resource注解在Spring安装目录的lib\j2ee\common-annotations.jar

使用@Autowired注解的业务代码如下:
package com.bill.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.bill.PersonService;
import com.bill.dao.PersonDao;
/**
 * @author Bill
 */
public class PersonServiceBean implements PersonService {
	//默认按类型装配
	@Autowired private PersonDao personDao;
	//使用@Qualifier("personDao")将@Autowired装配方式改为按名称装配
	//@Autowired @Qualifier("personDao") private PersonDao personDao;
	public void save(){
		personDao.add();
	}
}


二、注入类型
1、基本类型以及集合类型对象注入
public class PersonServiceBean implements PersonService {
	private String name;
	private Integer id;
	private Set<String> sets = new HashSet<String>();
	private Map<String, String> maps = new HashMap<String, String>();
	private Properties properties = new Properties();
	
	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	public Properties getProperties() {
		return properties;
	}

	public void setProperties(Properties properties) {
		this.properties = properties;
	}

	public Map<String, String> getMaps() {
		return maps;
	}

	public void setMaps(Map<String, String> maps) {
		this.maps = maps;
	}

	public Set<String> getSets() {
		return sets;
	}

	public void setSets(Set<String> sets) {
		this.sets = sets;
	}
}

	<bean id="personService" class="com.bill.impl.PersonServiceBean">
		<property name="name" value="bill"/>
		<property name="id" value="88"/>
		<property name="sets">
			<set>
				<value>set1</value>
				<value>set2</value>
				<value>set3</value>
			</set>
		</property>
		<property name="maps">
			<map>
				<entry key="key1" value="value1"></entry>
				<entry key="key2" value="value2"></entry>
				<entry key="key3" value="value3"></entry>
			</map>
		</property>
		
		<property name="properties">
			<props>
				<prop key="key-1">propValue1</prop>
				<prop key="key-2">propValue2</prop>
				<prop key="key-3">propValue3</prop>
			</props>
		</property>
	</bean>

测试代码:
		System.out.println("===========set============");
		for(String value : personService.getSets()){
			System.out.println(value);
		}
		System.out.println("===========map============");
		for(String key : personService.getMaps().keySet()){
			System.out.println(key + "=" + personService.getMaps().get(key));
		}
		System.out.println("===========properties========");
		for(Object propsKey : personService.getProperties().keySet()){
			System.out.println(propsKey + "=" + personService.getProperties().getProperty((String) propsKey));
		}


2、注入其他bean类型
1)方式一
	<bean id="personDao" class=" com.bill.dao.impl.PersonDaoBean"/>
	<bean id="personService" class="com.bill.impl.PersonServiceBean">
		<property name="personDao" ref="personDao"></property>
	</bean>

2)方式二(使用内部bean的方式进行注入,但该bean不能被其他bean使用)
	<bean id="personService" class="com.bill.impl.PersonServiceBean">
		<property name="personDao">
			<bean class=" com.bill.dao.impl.PersonDaoBean"/>
		</property>
	</bean>
分享到:
评论

相关推荐

    自定义依赖注入工具类SpringUtil.java

    自定义依赖注入工具类SpringUtil.java

    Spring系列之依赖注入的三种方式.docx

    如果需要给该bean提供一些初始化参数,则需要通过依赖注入方式,所谓的 依赖注入就是通过spring将bean所需要的一些参数传递到bean实例对象的过程(将依赖关系注入到对象中) ,spring的依赖注入有3种方式: ...

    Spring依赖注入检查.

    Spring依赖注入检查,适合初学者进一步了解Spring框架。

    用Spring注入Servlet文件 实现注入set

    使用spring的依赖注入,来实现servlet中注入dao层

    spring依赖注入

    涉及到spring依赖注入包括属性注入和对象注入

    Spring中依赖注入与容器

    一个组件(对象)的运行需要用到另一个组件(对象),称这种关系为依赖关系  举例:鱼依赖水,生命依赖空气、阳光、水、食物 组件依赖的资源(其他组件)由所在环境(上下文、容器)传递进去  依赖注入的几种形式...

    详解Spring的核心机制依赖注入

    详解Spring的核心机制依赖注入 对于一般的Java项目,他们都或多或少有一种依赖型的关系,也就是由一些互相协作的对象构成的。Spring把这种互相协作的关系称为依赖关系。如A组件调用B组件的方法,可称A组件依赖于B...

    spring依赖注入的理解.docx

    Spring中的依赖注入就是上面说的外部,实例不在由程序员实例化,而是通过spring容器帮我们new指定实例并且将实例注入到需要该对象的类。 我们不用关心Car的变化,实例之间的依赖关系由IOC容器负责了,等待Spring...

    探秘Spring框架解决循环依赖的高效策略

    二级缓存(earlySingletonObjects)存储提前暴露的对象,允许注入到其他bean中,即使它们还没完全初始化。三级缓存(singletonFactories)则存储对象工厂,用于生成代理对象,解决AOP相关的循环依赖。通过这三级缓存...

    Spring4快速学习步骤

    本章学习目标  Spring 框架简介  SpringIOC 的概念和作用  工厂模式设计一个简单的IOC 容器 ... SpringIOC 的XML 方式依赖注入  SpringIOC 的注解方式  Spring 整合Junit 简化测试类编写

    spring 对象管理ppt

    介绍spring的对象管理技术,spring的依赖注入,spring的值传递

    Spring——IOC(控制反转)与DI(依赖注入).docx

    IOC与DI的理解及使用 控制反转IOC(Inversion of Control)是一种设计思想,DI(依赖注入)是实现IOC的一种方法 。... 在Spring中实现控制反转的是IOC容器 ,其 实现方法是依赖注入 (Dependency Injection,DI)

    第一个Spring程序(DI的实现).docx

    依赖注入:Dependency Injection(DI)与控制反转(IoC),不同角度但是同一个...在spring容器的角度看来,spring容器负责将被依赖对象赋值给成员变量,这相当于为实例对象注入了它所依赖的实例,这是spring的依赖注入。

    JAVAspring学习资料

    其中最核心的模块是Spring Core,它提供了IoC(控制反转)和DI(依赖注入)的功能,使得对象之间的依赖关系由框架来管理,降低了组件之间的耦合度。 Java Spring还包括以下重要模块: Spring MVC:用于构建Web应用...

    spring1.2学习心得分享

    Spring容器的特点 (1)容器对对象的管理 a.创建时机:默认和容器一起创建。... Dependecy Injection 依赖注入 Spring 使用DI技术实现了IoC控制。 a.setter注入 b.构造注入 c.接口注入(以后了解)

    Java代码实现依赖注入

    模仿Spring实现一种基于xml配置文件的依赖注入机制。文件中将实现3中注入,一是单值注入,包括int,float,double,char等,也包括String注入;二是Java容器注入,包括List,Set,Map三种容器的注入,最后一种是java ...

    .NET Autofac依赖注入

    依赖注入又称之为控制反转(Inversion of Control,英文缩写为IoC)是一个重要的面向对象编程的法则来削减计算机程序的耦合问题,也是轻量级的Spring框架的核心。 控制反转一般分为两种类型,依赖注入(Dependency ...

    Spring插件安装图解

    轻量级:Spring 是非侵入性的 - 基于 Spring 开发的应用中的对象可以不依赖于 Spring 的 API 依赖注入(DI --- dependency injection、IOC) 面向切面编程(AOP --- aspect oriented programming) 容器: Spring 是一个...

    SSM相关面试题(包括Spring,SpringMVC,Mybaits在内的50道面试题)

    以前是由自己控制它所引用对象的生命周期,而在IOC中,所有的对象都被 Spring 控制,控制对象生命周期的不再是引用它的对象,而是Spring容器,由 Spring 容器帮我们创建、查找及注入依赖对象,而引用对象只是被动的...

    springioc和spring aop

    控制反转(Inversion of Control,缩写为IoC),是面向对象编程中的一种设计原则,可以用来减低计算机代码之间的耦合度。其中最常见的方式叫做依赖注入(Dependency Injection,简称...也可以说,依赖被注入到对象中。

Global site tag (gtag.js) - Google Analytics