Spring框架常用注解@Autowired、@Resource、@Repository等等

Spring引入了注解,通过@注解名的方式,让注解与Java Bean紧密结合,既大大减少了配置文件的体积,又增加了Java Bean的可读性与内聚性。

Spring框架常用注解@Autowired、@Resource、@Repository等等

一、@Autowired和@Resource注解

@Autowired注解的意思就是,当Spring发现@Autowired注解时,将自动在代码上下文中找到与其匹配(默认是类型匹配)的Bean,并自动注入到相应的地方去。

@Resource的装配顺序:

1. @Resource后面没有任何内容,默认通过name属性去匹配bean,找不到再按type去匹配。

2. 指定了name或者type则根据指定的类型去匹配bean。

3. 指定了name和type则根据指定的name和type去匹配bean,任何一个不匹配都会报错。


@Autowired和@Resource两个注解的区别:

1. @Autowired默认按照byType方式进行bean匹配,@Resource默认按照byName方式进行bean匹配。

2. @Autowired是Spring的注解,@Resource是J2EE的注解,根据导入注解的包名就可以知道。

二、@Repository、@Service、@Controller注解

Spring框架常用注解@Autowired、@Resource、@Repository等等

Spring的注解形式:@Repository、@Service、@Controller,它们分别对应存储层Bean,业务层Bean,和展示层Bean。

@Controller 用于标记在一个类上,使用它标记的类就是一个SpringMVC Controller 对象。

@Component是一个通用的Spring容器管理的单例bean组件,而@Repository, @Service, @Controller就是针对不同的使用场景所采取的特定功能化的注解组件。

相关推荐