系统入门云计算服务,项目上云最佳实践
@Autowired与@Resource都是我们日常开发中常用的两个注解,那么它们之间终究有何区别呢?
- 开端解说之前我们首先要明白一点,这个两个注解都是用来完成组件的装配的,即应用依赖注入(DI),完成对ioc容器当中各个组件之间依赖的装配赋值。
来源:@Autowired为Spring提供的注解,需求导入包org.springframework.beans.factory.annotation.Autowired。
阐明:@Autowired采取的默许战略为依照类型注入(by-type)。请求容器中一定要有这个类型的对象,假如没有将会报错,抛出异常。也能够经过设置能够@Autowired(required = false),来通知容器,假如没有能够不注入。
示例:
public class StudentController { @Autowired private StudentServer studentServer; }复制代码如上代码所示,这样装配会去spring容器中找到类型为StudentServer的类,然后将其注入进来。这样会产生一个问题,当容器中有多个相同类型的对象,会形成无法选择详细注入哪一个的状况从而招致报错,这个时分我们能够经过@Qualifier("beanname"),来指定装配哪个对象。
public class StudentController { @Autowired @Qualifier(name="studentServer") private StudentServer studentServer; }复制代码@Qualifier注解会通知spring去装配StudentServer对象。这个时分我们就能够胜利注入正确的对象了。
@Resource注解
来源:@Resource注解由J2EE提供,需求导入包javax.annotation.Resource。
阐明:@Resource能够设置by-name(按称号)和by-type(按类型)来停止自动装配。假如没指定则默许依照ByName自动注入。
示例:
public class StudentController { @Resource private StudentServer studentServer; }复制代码没有指定name,又没有指定type,该注解会自动依照by-name方式停止装配,假如匹配则自动装配。假如没有匹配,则依照by-type停止查找,假如都没查找到,那么则抛出异常。
public class StudentController { @Resource(name="studentServer") private StudentServer studentServer; }复制代码指定了name,则从上下文中查找称号(id)匹配的bean停止装配,找不到则抛出异常。
public class StudentController { @Resource(type="StudentServer") private StudentServer studentServer; }复制代码指定了type,则从上下文中找到相似匹配的独一bean停止装配,找不到或是找到多个,都会抛出异常。
public class StudentController { @Resource(name="studentServer",type="StudentServer") private StudentServer studentServer; }复制代码同时指定了name和type,则从Spring上下文中找到独一匹配的bean停止装配,找不到则抛出异常。
总结
@Autowired是Spring的注解经过类型(type)来完成装配Bean,也能够经过称号(name)来装配Bean(需求配合@Qualifier("beanname")运用)。依赖对象必需存在,假如要允许null值,能够设置它的required属性为false @Autowired(required=false)。
@Resource是J2EE的注解是Java自已的东西运用@Resource能够减少代码和Spring之间的耦合。它能够经过by-type来完成装配Bean,也能够by-name停止装配,假如指定了则依照指定的停止装配,假如都没指定的话先by-name 后by-type 也能够同时指定by-name与by-type。
链接:https://pan.baidu.com/s/1lZUBIvbzBm48u_DhOHdWPA
提取码:mb8p
--来自百度网盘超级会员V4的分享


雷达卡


京公网安备 11010802022788号







