spring之Annotation

spring除了提供了@Autowired,还提供了以下几类annotation。

1、@Component, @Repository, @Service, @Controller

      @Repository、@Service、@Controller在目前的 Spring 版本中,这 3 个注释和 @Component 是一样的,但是从注释类的命名上,很容易看出这 3 个注释分别和持久层、业务层和控制层(Web 层)相对应。虽然目前这 3 个注释和 @Component 相比没有什么新意,但 Spring 将在以后的版本中为它们添加特殊的功能。所以,如果Web 应用程序采用了经典的三层分层结构的话,最好在持久层、业务层和控制层分别采用

     相当于xml中配置的bean,key默认的就是首字母小写的类名

也可以手动指定key,@service("xxx")相当于@service(name="xxx")

2、@scope

相当于xml中配置的scope属性,有五种类型,singleton,prototype,request,session,global session,可参考前面写的spring之scope。

  

3、@PreDestroy,@PostConstruct

@PostConstruct相当于xml中配置的init-method,@PreDestroy相当于xml中配置的destroy-method。可参考写的spring之生命周期。

配置如下

4、组件扫描配置

在spring中使用注解annotation,就不需要在xml中配置bean了,但是需要配置组件扫描,这样spring就会把注解了这些annotation的类当做一个bean来处理。

back-package="xxx",xxx表示需要扫描的包。

原文地址:https://www.cnblogs.com/pjfmeng/p/7552544.html