Spring自带的@Component注解及扩展@Repository、@Service、@Controller,如图

Spring bean注解配置(1)

在使用注解方式配置bean时,需要引进一个包:

Spring bean注解配置(1)

使用方法:

1、为需要使用注解方式的类添加注解标记

@Component("标识符")  
POJO类  

在类上使用@Component注解,表示该类定义为Spring管理Bean,使用默认value(可选)属性表示Bean标识符。如果不指定标识符,默认为首字母小写类名。例如类UserController的标识符为userController

 

2、在xml中配置自动扫描策略

1 <context:component-scan
2         base-package=""
3         resource-pattern="**/*.class"
4         name-generator="org.springframework.context.annotation.AnnotationBeanNameGenerator"
5         use-default-filters="true"
6         annotation-config="true">
7                 <context:include-filter type="aspectj" expression=""/>
8                 <context:exclude-filter type="regex" expression=""/>
9 </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/>开启。

  • <context:include-filter>表示过滤到的类将被注册为Spring管理Bean。需要配合use-default-filters使用

  • <context:exclude-filter>表示过滤到的类将不被注册为Spring管理Bean,它比<context:include-filter>具有更高优先级;

  • type表示过滤器类型,目前支持注解类型、类类型、正则表达式、aspectj表达式过滤器,当然也可以自定义自己的过滤器,实现org.springframework.core.type.filter.TypeFilter即可;

  • expression表示过滤器表达式。

 

下面为案例分析:

 

1 package com.proc.bean;
2 
3 import org.springframework.stereotype.Component;
4 
5 @Component
6 public class TestObject {
7 
8 }
TestObject

相关文章:

  • 2021-12-31
  • 2022-12-23
  • 2022-12-23
  • 2021-12-12
  • 2021-05-21
  • 2021-04-03
  • 2022-01-01
猜你喜欢
  • 2021-09-25
  • 2022-12-23
  • 2021-11-18
  • 2021-12-01
  • 2021-08-24
  • 2022-12-23
相关资源
相似解决方案