`

Spring Bean配置:注解配置

阅读更多

Spring提供通过扫描类路径中的特殊注解类来自动注册Bean定义。同注解驱动事务一样需要开启自动扫描并注册Bean定义支持,使用方式如下(resources/chapter12/ componentDefinitionWithAnnotation.xml):

<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns:aop="http://www.springframework.org/schema/aop"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xsi:schemaLocation="   
       http://www.springframework.org/schema/beans   
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
       http://www.springframework.org/schema/aop   
       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
       http://www.springframework.org/schema/context   
       http://www.springframework.org/schema/context/spring-context-3.0.xsd">   

    <aop:aspectj-autoproxy />   

    <context:component-scan base-package="cn.javass.spring.chapter12"/>   

</beans>  

使用标签来表示需要要自动注册Bean定义,而通过base-package属性指定扫描的类路径位置。

   <context:component-scan>标签将自动开启“注解实现Bean依赖注入”支持。
   此处我们还通过<aop:aspectj-autoproxy/>用于开启Spring对@AspectJ风格切面的支持。

Spring基于注解实现Bean定义支持如下三种注解:

Spring自带的

@Component注解及扩展@Repository、@Service、@Controller

如图12-1所示;
JSR-250 1.1版本中中定义的@ManagedBean注解,是Java EE 6标准规范之一,不包括在JDK中,需要在应用服务器环境使用(如Jboss),如图12-2所示;
JSR-330的@Named注解,如图12-3所示。

这里写图片描述

图12-1 Spring自带的@Component注解及扩展

这里写图片描述

图12-2 JSR-250中定义的@ManagedBean注解及自定义扩展

这里写图片描述

图12-3 JSR-330的@Named注解及自定义扩展

 

图12-2和图12-3中的自定义扩展部分是为了配合Spring自带的模式注解扩展自定义的,并不包含在Java EE 6规范中,在Java EE 6中相应的服务层、DAO层功能由EJB来完成。

在Java EE中有些注解运行放置在多个地方,如@Named允许放置在类型、字段、方法参数上等,因此一般情况下放置在类型上表示定义,放置在参数、方法等上边一般代表使用(如依赖注入等等)。

12.3.2 Spring自带的@Component注解及扩展
一、@Component:定义Spring管理Bean,使用方式如下:

@Component("标识符")  
POJO类 

在类上使用@Component注解,表示该类定义为Spring管理Bean,使用默认value(可选)属性表示Bean标识符。

1、定义测试Bean类:

package cn.javass.spring.chapter12;   
import org.springframework.beans.factory.annotation.Autowired;   
import org.springframework.context.ApplicationContext;   
import org.springframework.stereotype.Component;   
@Component("component")   
public class TestCompoment {   
    @Autowired  
    private ApplicationContext ctx;   
    public ApplicationContext getCtx() {   
        return ctx;   
    }   
}  

 

2、Spring配置文件使用chapter12/ componentDefinitionWithAnnotation.xml即可且无需修改;

3、定义测试类和测试方法:

package cn.javass.spring.chapter12;   
//省略import   
public class ComponentDefinitionWithAnnotationTest {   
    private static String configLocation = "classpath:chapter12/componentDefinitionWithAnnotation.xml";   
    private static ApplicationContext ctx = new ClassPathXmlApplicationContext(configLocation);   
    @Test  
    public void testComponent() {   
        TestCompoment component = ctx.getBean("component", TestCompoment.class);   
        Assert.assertNotNull(component.getCtx());   
    }   
} 

 

测试成功说明被@Component注解的POJO类将自动被Spring识别并注册到Spring容器中,且自动支持自动装配。

@AspectJ风格的切面可以通过@Compenent注解标识其为Spring管理Bean,而@Aspect注解不能被Spring自动识别并注册为Bean,必须通过@Component注解来完成,示例如下:

 

package cn.javass.spring.chapter12.aop;   
//省略import   
@Component  
@Aspect  
public class TestAspect {   
    @Pointcut(value="execution(* *(..))")   
    private void pointcut() {}   
    @Before(value="pointcut()")   
    public void before() {   
        System.out.println("=======before");   
    }   
}

 

通过@Component将切面定义为Spring管理Bean。

二、@Repository:@Component扩展,被@Repository注解的POJO类表示DAO层实现,从而见到该注解就想到DAO层实现,使用方式和@Component相同;

1、定义测试Bean类:

package cn.javass.spring.chapter12.dao.hibernate;   
import org.springframework.stereotype.Repository;   
@Repository("testHibernateDao")   
public class TestHibernateDaoImpl {   
}  

 

2、Spring配置文件使用chapter12/ componentDefinitionWithAnnotation.xml即可且无需修改;

3、定义测试方法:

@Test  
public void testDao() {   
TestHibernateDaoImpl dao =   
ctx.getBean("testHibernateDao", TestHibernateDaoImpl.class);   
Assert.assertNotNull(dao);   
}

 

测试成功说明被@Repository注解的POJO类将自动被Spring识别并注册到Spring容器中,且自动支持自动装配,并且被@Repository注解的类表示DAO层实现。

三、@Service:@Component扩展,被@Service注解的POJO类表示Service层实现,从而见到该注解就想到Service层实现,使用方式和@Component相同;

1、定义测试Bean类:

package cn.javass.spring.chapter12.service.impl;   
import org.springframework.beans.factory.annotation.Autowired;   
import org.springframework.beans.factory.annotation.Qualifier;   
import org.springframework.stereotype.Service;   
import cn.javass.spring.chapter12.dao.hibernate.TestHibernateDaoImpl;   
@Service("testService")   
public class TestServiceImpl {   
    @Autowired  
    @Qualifier("testHibernateDao")   
    private TestHibernateDaoImpl dao;   
    public TestHibernateDaoImpl getDao() {   
        return dao;   
    }   
} 

 

2、Spring配置文件使用chapter12/ componentDefinitionWithAnnotation.xml即可且无需修改;

3、定义测试方法:

@Test  
public void testService() {   
    TestServiceImpl service = ctx.getBean("testService", TestServiceImpl.class);   
    Assert.assertNotNull(service.getDao());   
}  

 

测试成功说明被@Service注解的POJO类将自动被Spring识别并注册到Spring容器中,且自动支持自动装配,并且被@Service注解的类表示Service层实现。

四、@Controller:@Component扩展,被@Controller注解的类表示Web层实现,从而见到该注解就想到Web层实现,使用方式和@Component相同;

1、定义测试Bean类:

package cn.javass.spring.chapter12.action;   
//省略import   
@Controller  
public class TestAction {   
    @Autowired  
    private TestServiceImpl testService;   

    public void list() {   
        //调用业务逻辑层方法   
    }   
}   

 

2、Spring配置文件使用chapter12/ componentDefinitionWithAnnotation.xml即可且无需修改;

3、定义测试方法:

@Test  
public void testWeb() {   
    TestAction action = ctx.getBean("testAction", TestAction.class);   
    Assert.assertNotNull(action);   
}  

 

测试成功说明被@Controller注解的类将自动被Spring识别并注册到Spring容器中,且自动支持自动装配,并且被@Controller注解的类表示Web层实现。

大家是否注意到@Controller中并没有定义Bean的标识符,那么默认Bean的名字将是以小写开头的类名(不包括包名),即如“TestAction”类的Bean标识符为“testAction”。

六、自定义扩展:Spring内置了三种通用的扩展注解@Repository、@Service、@Controller ,大多数情况下没必要定义自己的扩展,在此我们演示下如何扩展@Component注解来满足某些特殊规约的需要;

在此我们可能需要一个缓存层用于定义缓存Bean,因此我们需要自定义一个@Cache的注解来表示缓存类。

1、扩展@Component:

package cn.javass.spring.chapter12.stereotype;   
//省略import   
@Target({ElementType.TYPE})   
@Retention(RetentionPolicy.RUNTIME)   
@Documented  
@Component  
public @interface Cache{   
       String value() default "";   
}

 

扩展十分简单,只需要在扩展的注解上注解@Component即可,@Repository、@Service、@Controller也是通过该方式实现的,没什么特别之处

2、定义测试Bean类:

 

package cn.javass.spring.chapter12.cache;   
@Cache("cache")   
public class TestCache {   

} 

 

2、Spring配置文件使用chapter12/ componentDefinitionWithAnnotation.xml即可且无需修改;

3、定义测试方法:

@Test  
public void testCache() {   
    TestCache cache = ctx.getBean("cache", TestCache.class);   
    Assert.assertNotNull(cache);   
}  

 

测试成功说明自定义的@Cache注解也能很好的工作,而且实现了我们的目的,使用@Cache来表示被注解的类是Cache层Bean。

12.3.3 JSR-250中定义的@ManagedBean注解
@javax.annotation.ManagedBean需要在实现Java EE 6规范的应用服务器上使用,虽然Spring3实现了,但@javax.annotation.ManagedBean只有在Java EE 6环境中才有定义,因此测试前需要我们定义ManagedBean类。

1、定义javax.annotation.ManagedBean注解类:

package javax.annotation;   
import java.lang.annotation.ElementType;   
import java.lang.annotation.Retention;   
import java.lang.annotation.RetentionPolicy;   
import java.lang.annotation.Target;   
@Target(ElementType.TYPE)   
@Retention(RetentionPolicy.RUNTIME)   
public @interface ManagedBean {   
     String value() default "";   
} 

 

其和@Component完全相同,唯一不同的就是名字和创建者(一个是Spring,一个是Java EE规范)。

2、定义测试Bean类:

package cn.javass.spring.chapter12;   
import javax.annotation.Resource;   
import org.springframework.context.ApplicationContext;   
@javax.annotation.ManagedBean("managedBean")   
public class TestManagedBean {   
    @Resource  
    private ApplicationContext ctx;   
    public ApplicationContext getCtx() {   
        return ctx;   
    }   
}  

 

2、Spring配置文件使用chapter12/ componentDefinitionWithAnnotation.xml即可且无需修改;

3、定义测试方法:

@Test  
public void testManagedBean() {   
    TestManagedBean testManagedBean = ctx.getBean("managedBean", TestManagedBean.class);   
    Assert.assertNotNull(testManagedBean.getCtx());   
}  

 

测试成功说明被@ManagedBean注解类也能正常工作。

自定义扩展就不介绍了,大家可以参考@Component来完成如图12-2所示的自定义扩展部分。

12.3.4 JSR-330的@Named注解
@Named不仅可以用于依赖注入来指定注入的Bean的标识符,还可以用于定义Bean。即注解在类型上表示定义Bean,注解在非类型上(如字段)表示指定依赖注入的Bean标识符。

1、定义测试Bean类:

package cn.javass.spring.chapter12;   
//省略import   
@Named("namedBean")   
public class TestNamedBean {   
    @Inject  
    private ApplicationContext ctx;   
    public ApplicationContext getCtx() {   
        return ctx;   
    }   
}

 

2、Spring配置文件使用chapter12/ componentDefinitionWithAnnotation.xml即可且无需修改;

3、定义测试方法:

@Test  
public void testNamedBean() {   
TestNamedBean testNamedBean =   
    ctx.getBean("namedBean", TestNamedBean.class);   
    Assert.assertNotNull(testNamedBean.getCtx());   
}

 

测试成功说明被@Named注解类也能正常工作。

自定义扩展就不介绍了,大家可以参考@Component来完成如图12-3所示的自定义扩展部分。

12.3.5 细粒度控制Bean定义扫描
在XML配置中完全消除了Bean定义,而是只有一个标签来支持注解Bean定义扫描。

前边的示例完全采用默认扫描设置,如果我们有几个组件不想被扫描并自动注册、我们想更改默认的Bean标识符生成策略该如何做呢?接下来让我们看一下如何细粒度的控制Bean定义扫描,具体定义如下:

 

<context:component-scan   
        base-package=""  
        resource-pattern="**/*.class"  
        name-generator="org.springframework.context.annotation.AnnotationBeanNameGenerator"  
        use-default-filters="true"  
        annotation-config="true">   
                <context:include-filter type="aspectj" expression=""/>   
                <context:exclude-filter type="regex" expression=""/>   
</context:component-scan> 

 

base-package:表示扫描注解类的开始位置,即将在指定的包中扫描,其他包中的注解类将不被扫描,默认将扫描所有类路径;
resource-pattern:表示扫描注解类的后缀匹配模式,即“base-package+resource-pattern”将组成匹配模式用于匹配类路径中的组件,默认后缀为“*/.class”,即指定包下的所有以.class结尾的类文件;
name-generator:默认情况下的Bean标识符生成策略,默认是AnnotationBeanNameGenerator,其将生成以小写开头的类名(不包括包名);可以自定义自己的标识符生成策略;
use-default-filters:默认为true表示过滤@Component、@ManagedBean、@Named注解的类,如果改为false默认将不过滤这些默认的注解来定义Bean,即这些注解类不能被过滤到,即不能通过这些注解进行Bean定义;
annotation-config:表示是否自动支持注解实现Bean依赖注入,默认支持,如果设置为false,将关闭支持注解的依赖注入,需要通过开启。
默认情况下将自动过滤@Component、@ManagedBean、@Named注解的类并将其注册为Spring管理Bean,可以通过在标签中指定自定义过滤器将过滤到匹配条件的类注册为Spring管理Bean,具体定义方式如下:

 

<context:include-filter type="aspectj" expression=""/>  
<context:exclude-filter type="regex" expression=""/> 

:表示过滤到的类将被注册为Spring管理Bean;
:表示过滤到的类将不被注册为Spring管理Bean,它比具有更高优先级;
type:表示过滤器类型,目前支持注解类型、类类型、正则表达式、aspectj表达式过滤器,当然也可以自定义自己的过滤器,实现org.springframework.core.type.filter.TypeFilter即可;
expression:表示过滤器表达式。

一般情况下没必要进行自定义过滤,如果需要请参考如下示例:

1、cn.javass.spring.chapter12.TestBean14自动注册为Spring管理Bean:

<context:include-filter type="assignable" expression="cn.javass.spring.chapter12.TestBean14"/>  

2、把所有注解为org.aspectj.lang.annotation.Aspect自动注册为Spring管理Bean:

<context:include-filter type="annotation"  
expression="org.aspectj.lang.annotation.Aspect"/>  

3、将把匹配到正则表达式“cn.javass.spring.chapter12.TestBean2*”排除,不注册为Spring管理Bean:

<context:exclude-filter type="regex" expression="cn\.javass\.spring\.chapter12\.TestBean2*"/>

4、将把匹配到aspectj表达式“cn.javass.spring.chapter12.TestBean3*”排除,不注册为Spring管理Bean:

<context:exclude-filter type="aspectj" expression="cn.javass.spring.chapter12.TestBean3*"/>

 

具体使用就要看项目需要了,如果以上都不满足需要请考虑使用自定义过滤器。

12.3.6 提供更多的配置元数据
1、@Lazy:定义Bean将延迟初始化,使用方式如下:

@Component("component")  
@Lazy(true)  
public class TestCompoment {  
……  
}  

使用@Lazy注解指定Bean需要延迟初始化。

2、@DependsOn:定义Bean初始化及销毁时的顺序,使用方式如下:

@Component("component")  
@DependsOn({"managedBean"})  
public class TestCompoment {  
……  
}  

3、@Scope:定义Bean作用域,默认单例,使用方式如下:

@Component("component")  
@Scope("singleton")  
public class TestCompoment {  
……  
}

4、@Qualifier:指定限定描述符,对应于基于XML配置中的标签,使用方式如下:

@Component("component")  
@Qualifier("component")  
public class TestCompoment {  
……  
}  

可以使用复杂的扩展,如@Mysql等等。

5、@Primary:自动装配时当出现多个Bean候选者时,被注解为@Primary的Bean将作为首选者,否则将抛出异常,使用方式如下:

@Component("component")   
@Primary  
public class TestCompoment {   
……   
}
分享到:
评论

相关推荐

    spring bean XML配置入门

    在实际开发中,我们可以使用Eclipse的Spring插件来简化Bean配置的创建和管理,同时结合Maven来构建和运行Spring应用。 通过以上内容,你应该对Spring框架中的Bean XML配置有了初步的理解。掌握这些知识点后,你将...

    day38 16-Spring的Bean的装配:注解的方式

    1. **启用注解配置**:在Spring配置文件中添加`&lt;context:component-scan&gt;`标签,指定要扫描的包,这样Spring会自动发现带有`@Component`及其派生注解的类。 ```xml &lt;context:component-scan base-package=...

    day38 17-Spring的Bean的属性注入:注解方式

    在Spring 2.5版本之后,引入了基于注解的配置,这使得我们可以直接在类或方法上使用注解来声明Bean及其属性。主要的注解有`@Component`、`@Service`、`@Repository`和`@Controller`,它们定义了Bean的角色,而`@...

    Spring的Bean配置

    在本文中,我们将深入探讨Spring中的Bean配置,包括IoC和DI的概念,Bean的配置方式,以及不同类型的IOC容器。 **Spring的Bean配置**: 在Spring中,Bean是应用中的对象,它们由Spring IoC容器负责创建、管理和装配...

    spring bean的生命周期

    - **注解配置**:使用`@Component`,`@Service`,`@Repository`和`@Controller`注解标记类,配合`@Autowired`,`@Qualifier`等注解进行依赖注入。 - **Java配置**:通过`@Configuration`和`@Bean`注解来定义Bean...

    Spring Bean创建初始化流程.docx

    开始时,通过`AnnotationConfigApplicationContext`类创建一个上下文实例,通常传入一个或多个配置类(`annotatedClasses`),这些类带有@Configuration注解,用于定义Bean的配置。 2. **刷新上下文**: 调用`...

    Spring bean 动态注册,jar包热替换

    Spring bean 一般通过配置文件和注解进行加载,如果要实现jar或class文件,动态实现spring bean 的动态加载,并通过UrlClassLoader完成jar和class文件的加载。可以实现jar的热替换。spring的bean动态加载则需要对...

    Spring Bean重复执行两次(实例被构造两次)问题分析

    解决这个问题的关键在于深入理解Spring的Bean生命周期和配置机制,检查配置文件、注解使用、依赖关系等,确保每个Bean的定义都是唯一的,且作用域设置正确。同时,对源码进行调试也是一个有效的排查手段,可以追踪到...

    spring配置文件----注解配置

    本主题聚焦于Spring框架的配置文件以及其中的注解配置方式。注解配置是Spring框架的一种简化配置手段,它允许开发者通过在类或方法上添加特定的注解,替代传统的XML配置文件,使得代码更加简洁且易于维护。 首先,...

    在非spring注解类中使用spring容器中的bean_普通类中使用yml配置文件中的配置信息

    然而,在某些情况下,我们可能需要在非Spring注解的类中访问Spring容器中的Bean,或者在这些类中使用YAML配置文件中的配置信息。本篇将详细介绍如何在这样的场景下实现这一目标。 首先,让我们来理解如何在非Spring...

    Spring Bean 加载顺序 .

    Spring支持多种配置方式,包括XML、Java配置类(@Configuration)、注解(@Component、@Service等)以及通过@ConfigurationProperties处理YAML或Properties文件。在实验小例子中,我们可能看到这几种配置方式的组合...

    Spring bean 管理

    - Bean的配置: - id和name:id属性是Bean的标识符,name属性可以包含特殊字符,且可以有多个别名。 - class:用于指定Bean所对应的完整类名,Spring通过反射来创建该类的实例。 3. Bean的作用域: - singleton...

    spring bean 属性总结

    Spring通过XML配置文件或注解来定义、配置和管理Beans。下面将深入探讨`&lt;beans&gt;`、`&lt;bean&gt;`及其属性,以及其他相关的配置元素。 #### `&lt;beans&gt;` 根元素 `&lt;beans&gt;`元素是Spring配置文件的根元素,用于封装一个或多...

    实例化Spring bean的两种工厂方法

    实例化Spring Bean的方式多种多样,包括XML配置、注解配置以及Java配置等。而工厂方法是其中一种自定义实例化过程的方法。 1. **实例工厂方法** 实例工厂方法是通过一个具体的工厂类实例来创建Spring Bean。在...

    详解Spring 中如何控制2个bean中的初始化顺序

    例如,可以使用 Spring 的 @Order 注解来指定 bean 的初始化顺序,也可以使用 Spring 的生命周期接口(如 InitializingBean)来控制 bean 的初始化顺序。 总结 控制 2 个 bean 的初始化顺序是一个常见的问题,本篇...

    spring3零配置注解实现Bean定义(包括JSR-250、JSR-330)

    ### Spring3零配置注解实现Bean定义 #### 概述 在Spring框架中,传统的Bean定义方式主要依赖于XML配置文件。随着技术的发展与需求的变化,Spring为了简化配置过程,引入了注解的方式进行Bean的定义。这不仅减少了...

    Spring框架xml注解配置方式实例

    在本实例中,我们将深入探讨如何使用XML和注解结合的方式来配置Spring框架。首先,我们先来理解每个文件的作用。 1. **Maven配置文件pom.xml** Maven是一个项目管理工具,通过pom.xml文件来管理项目的构建、依赖和...

    Spring Bean简单应用实例

    在提供的“BeanTest”文件中,我们可以预期看到一个简单的Spring Bean配置和测试示例。通常,这将包括以下部分: 1. **Bean定义**:Bean定义是Spring容器如何创建和管理Bean的描述。它可以是一个XML配置文件中的...

Global site tag (gtag.js) - Google Analytics