`

基于注解的依赖注入(零配置)

阅读更多

基于注解的依赖注入(零配置)
基于注解(Annotation)的配置有越来越流行的趋势,注解配置先对于XML配置具有很多的优势:
它可以充分利用java的反射机制获取类结构信息,这些信息可以有效减少配置的工作。
注释和java文件处于同一个文件中,而XML配置采用独立的配置文件,大多数配置文 件信息在程序开发完成后不会调整,如果配置信息和java代码放在一起,有助于增强 程序的内聚性。而采用独立的XML配置文件,程序员在编写一个功能时,往往需要在 程序文件和配置文件中不停切换,这种思维上的不连贯会降低开发效率。
开发步骤:
导入common-annotations.jar架包
在ApplicationContext.xml中加入命名空间
Eg:

<?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>  

 


Resource注解
以前我们通过xml文件方式表示Bean之间的依赖关系,而现在我们可以通过@Resource方式来标识Bean之间的依赖关系。
Person.java、

package net.battier.pojo;  
  
import java.io.Serializable;  
  
import javax.annotation.Resource;  
  
public class Person implements Serializable {  
    private static final long serialVersionUID = 1L;  
    private int id;  
    private String personName;  
    private boolean personSex;  
    private int personAge;  
    private String personDesc;  
    // 通过@Resource方式将配置文件中id为org的Bean注入给属性org;  
    //这种方式替代了xml文件中以ref关联Bean的方式。  
    @Resource(name="org")  
    private Organization org;  
  
    public int getId() {  
        return id;  
    }  
  
    public void setId(int id) {  
        this.id = id;  
    }  
  
              。。。  
  
}  

 
在配置文件ApplicationContext.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 />  
    <!-- Organization -->  
    <bean id="org" class="net.battier.pojo.Organization"></bean>  
    <!-- Person (这里不再注入org,而是在类中通过注解方式进行注入)-->  
    <bean id="person" class="net.battier.pojo.Person"></bean>  
</beans>  

 

@PostConstruct和@PreDestroy注解
这两个是定制Bean的生命周期行为的,除了这两个,还可以通过实现InitializingBean或者DispasableBean接口来定制初始化或者销毁的行为,另外还可以在配置文件中,每个Bean的节点里加入init-method或者destroy-method来操作
Chinese.java

package net.battier.dao.impl;  
  
import javax.annotation.PostConstruct;  
import javax.annotation.PreDestroy;  
  
import net.battier.dao.Axe;  
import net.battier.dao.Person;  
  
import org.springframework.beans.factory.DisposableBean;  
import org.springframework.beans.factory.InitializingBean;  
  
public class Chinese implements Person, InitializingBean, DisposableBean {  
  
    private Axe axe;  
  
    public Chinese() {  
        System.out.println("Spring实例化主调Bean:Chinese实例...");  
    }  
  
    // 通过设值注入  
    public void setAxe(Axe axe) {  
        this.axe = axe;  
    }  
  
    @Override  
    public void userAxe() {  
        // TODO Auto-generated method stub  
        axe.chop();  
    }  
  
    @Override  
    public void afterPropertiesSet() throws Exception {  
        // TODO Auto-generated method stub  
        System.out.println("正在初始化。。。");  
    }  
  
    // 定义销毁之前的特定行为  
    public void destroy() {  
        System.out.println("我快要挂了...");  
    }  
  
    @PostConstruct  
    public void init() {  
        System.out.println("使用注解初始化Chinese");  
    }  
  
    @PreDestroy  
    public void destroy1() {  
        System.out.println("使用注解销毁Chinese");  
    }  
}  

 


ApplicationContext.xml
Java代码

<?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 />  
    <!-- 配置chinese的实例并加上初始化方法 init-method="init"-->  
    <bean id="chinese" class="net.battier.dao.impl.Chinese"  
        destroy-method="destroy">  
        <!-- 通过设置注入 -->  
        <property name="axe" ref="sleelAxe"></property>  
    </bean>  
    <!-- 配置stoneAxe实例 -->  
    <bean id="sleelAxe" class="net.battier.dao.impl.SleelAxe"></bean>  
</beans>  

 


@Component注解
虽然我们可以通过@Resource在Bean类中使用自动注入功能,但是Bean还是在XML文件中通过<bean.../>进行定义,也就是说,在XML配置文件中定义Bean,通过@Resource为Bean的成员变量,方法入参提供自动注入的功能,能否也通过注解定义Bean,从XML配置文件中完全移除Bean定义的配置呢?答案是肯定的。

Organization.java

package net.battier.pojo;  
  
import java.io.Serializable;  
  
import org.springframework.stereotype.Component;  
  
@Component("org")  
public class Organization implements Serializable {  
    private static final long serialVersionUID = 1L;  
    private int id;  
    private String orgName;  
    private String parent;  
    private String orgCode;  
    private String orgDesc;  
  
    public int getId() {  
        return id;  
    }  
  
    public void setId(int id) {  
        this.id = id;  
    }  
  
        ...  
  
}  

 

Person .java

package net.battier.pojo;  
  
import java.io.Serializable;  
  
import javax.annotation.Resource;  
  
import org.springframework.stereotype.Component;  
  
@Component("person")  
public class Person implements Serializable {  
    private static final long serialVersionUID = 1L;  
    private int id;  
    private String personName;  
    private boolean personSex;  
    private int personAge;  
    private String personDesc;  
  
    // 通过@Resource方式将配置文件中id为org的Bean注入给属性org;  
    // 这种方式替代了xml文件中以ref关联Bean的方式。  
    @Resource(name = "org")  
    private Organization org;  
  
    public int getId() {  
        return id;  
    }  
  
    public void setId(int id) {  
        this.id = id;  
    }  
  
        ...  
  
  
}  

 


配置文件(注意要定义类扫描器,不需要命名空间)

<?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:component-scan base-package="net.battier.pojo"></context:component-scan>  
  
    <!-- Organization 使用了@Component注释,不需要在XML中配置了-->  
    <!--  <bean id="org" class="net.battier.pojo.Organization"></bean> -->  
  
    <!-- Person (这里不再注入org,而是在类中通过注解方式进行注入)-->  
    <!-- 使用了@Component注释,不需要在XML中配置了 -->  
    <!-- <bean id="person" class="net.battier.pojo.Person"></bean> -->  
</beans>  

 


在定义类扫描器
<context:component-scan base-package="net.battier.pojo">
</context:component-scan>
时,指定了要扫描的包下的类名,<context:component-scan/>还允许定义过滤器,从而将基包下的某些类纳入或排除。Spring支持四种类型的过滤方式:
注释:假如net.battier.Person是一个注解类,我们可以将使用该注解的类过滤出来。
类名指定:通过全限定类名进行过滤,如可以将某个类纳入扫描,也可以将某个类排除在外。
正则表达式:通过正则表达式定义过滤的类
AspectJ表达式:通过AspectJ标识定义过滤的类
Eg:

<context:component-scan base-package="net.battier.pojo">  
    <context:include-filter type="regex"     expression="net\.battier\.service\.."/>  
    <context:exclude-filter type="aspectj" expression="net.battier.util.."/>  
</context:component-scan>  

 




@Scope注释
默认情况下,@Component定义的Bean都是Singleton的,如果需要使用其他作用范围的Bean,可以通过@Scope来定义。

package net.battier.pojo;  
  
import java.io.Serializable;  
  
import javax.annotation.Resource;  
  
import org.springframework.context.annotation.Scope;  
import org.springframework.stereotype.Component;  
  
@Component("person")  
@Scope("Singleton")  
public class Person implements Serializable {  
    private static final long serialVersionUID = 1L;  
    private int id;  
    private String personName;  
    private boolean personSex;  
    private int personAge;  
    private String personDesc;  
  
    // 通过@Resource方式将配置文件中id为org的Bean注入给属性org;  
    // 这种方式替代了xml文件中以ref关联Bean的方式。  
    @Resource(name = "org")  
    private Organization org;  
  
    public int getId() {  
        return id;  
    }  
  
    public void setId(int id) {  
        this.id = id;  
    }  
  
    ...  
  
}     

 
其他注解
Spring2.5中除了提供@Component注解,还定义了几个拥有特殊语义的注解:@Reponsetory、@Service和@Controller.在目前的Spring版本中,这三个注解和@Component作用是等效的。但是从注解名上可以很清楚的看出3个注解分别对应:持久层(M)、业务层(V)、控制层(C),虽然目前这3个注解和@Component等效,但是Spring在以后的版本中为他们添加特殊的功能。所以如果项目分成了上述三层的话,最后在各个层中使用相应的注解。而@Component是对中立的类进行注解。

文章来源:

http://fendoubattier.iteye.com/blog/698777

 

分享到:
评论

相关推荐

    Spring与IoC系列四:基于注解的依赖注入.rar

    本系列文章聚焦于Spring与IoC(Inversion of Control,控制反转)容器,特别是第四部分,我们将深入探讨基于注解的依赖注入。 传统的Spring DI是通过XML配置文件来定义Bean及其依赖关系的。然而,随着Spring的发展...

    详解Spring基于Annotation的依赖注入实现

    在深入探讨Spring框架中基于注解(Annotation)的依赖注入(Dependency Injection,简称DI)实现之前,我们首先需要理解几个核心概念:Spring框架、依赖注入、以及注解本身。 ### Spring框架简介 Spring框架是一个...

    spring学习:依赖注入的几种方式讨论

    随着Java注解的流行,Spring引入了基于注解的DI。在类或方法上使用`@Autowired`注解可以自动匹配并注入依赖。例如: ```java @Service public class Service { @Autowired private Repository repository; } ``` ...

    使用反射和注解模拟Spring的依赖注入

    然而,实际的Spring框架提供了更高级的功能,如AOP(面向切面编程)、代理模式、基于XML或Java配置的bean定义、条件注解等,使得依赖注入更加灵活和强大。 总的来说,理解和掌握反射与注解对于深入学习Spring框架至...

    模仿Spring依赖注入

    3. **注解注入**:Spring 2.5引入了基于注解的依赖注入,可以更直观地标注需要注入的bean。例如,使用`@Autowired`注解,Spring会自动匹配类型或通过`@Qualifier`指定特定的bean。 ```java @Service public class ...

    (转)Spring 3.0 注解注入详解

    3. **@Required**:此注解用在字段或setter方法上,表示该字段或方法必须通过依赖注入来设置,否则容器启动时会抛出异常。这通常用于强制确保某些关键依赖被正确地注入。 4. **@Value**:这个注解可以用于注入基本...

    IOC之基于注解的配置bean(上)

    基于注解的配置是Spring实现IOC的一种方式,它减少了XML配置文件的使用,提高了开发效率。本篇文章将深入探讨如何在Spring中使用注解来配置Bean。 首先,我们需要了解Spring中的核心注解。`@Component`是基础注解,...

    spring依赖注入

    此外,Spring还提供了基于注解的配置,例如`@Service`、`@Repository`、`@Controller`用于标记业务层、数据访问层和控制层的bean,`@Component`用于标记一般组件。`@Autowired`注解自动将匹配类型的bean注入到字段或...

    spring famework 基于注解配置示例

    Spring框架是Java开发中广泛使用的轻量级框架,它的核心特性是依赖注入(Dependency Injection,简称DI)。在传统的XML配置方式下,我们通过编写大量的XML配置文件来定义bean及其依赖关系。然而,随着注解...

    基于注解的SSH整个框架

    Spring是Java应用程序的基础架构,它提供了依赖注入(DI)和面向切面编程(AOP)等核心功能。在基于注解的配置中,我们可以使用`@Autowired`注解来自动装配Bean,避免XML配置。此外,Spring MVC作为Spring的一部分...

    spring2.5基于注解例子程序

    综上所述,这个"spring2.5基于注解的例子程序"涵盖了Spring 2.5的核心特性,包括注解驱动的配置、自动扫描、基于注解的事务管理、AOP支持、MVC框架的使用,以及依赖注入等。通过学习和理解这个例子,开发者可以更好...

    Spring注解注入属性

    然而,随着Java注解的普及,Spring也引入了基于注解的依赖注入机制,简化了开发过程中的配置工作,提高了代码的可读性和可维护性。例如,在上述案例中,原本通过XML配置文件定义的`UserManagerImpl`和`UserDaoImpl`...

    Spring IOC之基于注解的容器配置.docx

    基于注解的配置是Spring框架提供的一种替代传统XML配置的方式,使得代码更加简洁,减少了XML配置文件的繁琐。 在Spring中,注解配置相较于XML配置有其独特的优点。注解可以嵌入到类、方法或字段上,为这些元素提供...

    spring依赖注入的实现原理

    依赖注入允许开发者在不修改代码的情况下,通过配置来改变对象间的依赖关系。它将对象的创建和对象之间依赖关系的管理交给了框架,使得系统更加灵活、易于测试和扩展。 ### 实现原理 1. **Bean工厂(Bean Factory)...

    spring+springmvc+jpa零配置注解开发

    然而,随着Spring的发展,它引入了基于注解的配置,使得我们可以完全摆脱XML,仅通过类上的注解就能完成配置。例如,我们可以在类上使用@Component、@Service、@Repository和@Controller注解来声明它们作为Spring...

    基于注解和Spring的多数据源配置和使用

    Spring框架广泛使用注解进行依赖注入、AOP(面向切面编程)以及其他功能的实现,使得代码更加简洁,更易于维护。 在Spring中,多数据源配置通常涉及以下几个关键步骤: 1. **数据源配置**:创建多个DataSource对象...

    Java-Spring各种依赖注入注解的区别.doc

    然而,这并不意味着注解无法注入XML配置的bean,因为依赖注入是在bean注册后进行的,所以XML配置的bean仍然可以接受注解注入。 最后,Spring的@Autowired注解在版本3.2.3.RELEASE中,其类型的自动装配机制可能根据...

Global site tag (gtag.js) - Google Analytics