spring注解支持

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

  • Spring自带的@Component注解及扩展@Repository、@Service、@Controller
  • JSR-250 1.1版本中中定义的@ManagedBean注解,是Java EE 6标准规范之一,不包括在JDK中,需要在应用服务器环境使用(如Jboss)
  • JSR-330的@Named注解

对应的Bean注入注解:

  • Spring的@Autowired
  • JSR-250的@Resource
  • JSR-330@Inject 

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,将关闭支持注解的依赖注入,需要通过<context:annotation-config/>开启。

默认情况下将自动过滤@Component、@ManagedBean、@Named注解的类并将其注册为Spring管理Bean,可以通过在<context:component-scan>标签中指定自定义过滤器将过滤到匹配条件的类注册为Spring管理Bean,具体定义方式如下:

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

详细配置<context:include-filter>和<context:exclude-filter>请见:<context:component-scan>

详细Bean定义注解请见:【第十二章】零配置 之 12.3 注解实现Bean定义 ——跟我学spring3

详细Bean注入注解请见:【第十二章】零配置 之 12.2 注解实现Bean依赖注入 ——跟我学spring3

详细Bean配置元数据注解请见:【第十二章】零配置 之 12.4 基于Java类定义Bean配置元数据 ——跟我学spring3

详细annotation-config含义解说请见:<context:annotation-config/>

原文地址:https://www.cnblogs.com/drizzlewithwind/p/5812760.html