注入依赖对象手工装配

来源:互联网 发布:dash for mac 破解版 编辑:程序博客网 时间:2024/06/16 10:58

依赖对象的注入分手工装配和自动装配两种方式,在不是很清楚装配结果的情况下,会产生不可预见性的结果,一般建议手工装配避免很多不必要的错误,而手工装配依赖对象的注入分两种情况:
1.使用bean.xml文件通过构造器或者setter方式装配,这样会是让bean的配置文件过于庞大
2.使用Java中的注解机制
bean.xml的方式在前面已经介绍过,现在使用注解方式需要哪些必要配置,如下:
一. 引入命名空间

<?xml version="1.0" encoding="UTF-8"?><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 /></beans>

2.引入jar文件:
lib\j2ee\common-annotations.jar
注意的是,在spring框架中使用@Autowired注解(默认按照类型查找,默认请情况下要要求依赖对象必须存在,如果允许为null,可以设置required的属性为false,如果想按照名名称装配,需要配合@Qualifier 一起使用)

@Autowired @Qualifier("personDao")    private PersonDao personDao; 
在J2EE 1.6中已经集成了注解@Resource,和@Autowired 一样,可以把注解标注到属性或者setter方法上,默认使用属性名称为查找的名称(默认按照名称查找,名称可以按照name指定,找不到名称按照类型查找)
    @Resource(name="personDao")    private PersonDao personDao;

example:把dao对象注入到service层上首先按照名称匹配,然后修改名称如下:
xml:

<context:annotation-config/><bean id="personDao" class="com.heying.dao.impl.PersonDaoBean"></bean>  <bean id="personService" class="com.heying.service.PersonServiceBean">    <!-- <property name="personDao" ref="personDao"></property>  --></bean>

service:

package com.heying.service;import javax.annotation.Resource;import com.heying.dao.PersonDao;public class PersonServiceBean implements PersonService{    @Resource    private PersonDao personDao; //没有new 对象,通过注入实现对象    public void save() {        personDao.add(); // 通过依赖注入使得对象由外部容器创建并管理    }}

结果:
这里写图片描述

修改注入的名称:

public class PersonServiceBean implements PersonService{@Resource    private PersonDao personDao123; //没有new 对象,通过注入实现对象    public void save() {        personDao123.add(); // 通过依赖注入使得对象由外部容器创建并管理        }}personDao123在spring容器中没有对象的结果,会按照类型查找,也可以通过修改xml文件,注意在@Resource(name="personDao")指定了name则不一样,注解也可以注在属性的setter方法上

结果:
这里写图片描述

下面介绍自动装配的方式:

<bean id="personDao" class="com.heying.dao.impl.PersonDaoBean"></bean>  <bean id="personService" class="com.heying.service.PersonServiceBean" autowire="byType/byName/constructor/autodetect"></bean><!-- 按照:类型,名称,构造器(与type方式相似,只是应用于构造器,没有相应的bean->exception,bean类的自省机智,使用构造器还是type) -->
0 0
原创粉丝点击