Python 官方文档:入门教程 => 点击学习
目录@Autowired@Resource总结应用场景@Resource和@Autowired是spring Framework中两种常用的注入方式,它们的作用是在Spring容器中
@Resource和@Autowired是spring Framework中两种常用的注入方式,它们的作用是在Spring容器中自动装配Bean对象.
@Autowired是Spring Framework提供的注解,它也可以实现自动装配Bean对象.
@RestController
public class DemoController {
@Autowired
DemoService demoService;
@Autowired
public void setDemoService(DemoService demoService) {
this.demoService = demoService;
}
}
@Autowired注解按照类型(byType)装配依赖对象,默认情况下它要求依赖对象必须存在,如果允许null值,可以设置它的required属性为false.如果我们想使用按照名称(byName)来装配,可以结合@Qualififier注解一起使用.如下:
@RestController
public class DemoController {
@Autowired
@Qualifier(value = "demoService")
DemoService demoService;
}
如果存在多个同类型的Bean对象,可以使用@Primary来指定一个默认的Bean对象,如下:
@RestController
public class DemoController {
@Autowired
DemoService demoService;
}
public interface DemoService {}
@Service
@Primary
public class DemoServiceImpl implements DemoService {}
@Service
public class DemoServiceImpl1 implements DemoService {}
@Resource默认按照byName自动注入,由JavaEE5提供.@Resource有两个重要的属性:name和type,而Spring将@Resource注解的name属性解析为bean的名字,而type属性则解析为bean的类型,所以,如果要使用name属性,则使用byName的自动注入策略,而使用type属性时则使用byType自动注入策略.如果即不指定name也不指定type,这时将通过反射机制使用byName自动注入策略.
@RestController
public class DemoController {
@Resource
DemoService demoService;
@Resource
public void setDemoService(DemoService demoService) {
this.demoService = demoService;
}
}
@Resource装配顺序:
区别
根据以上区别,我们可以根据具体情况选择使用@Resource或@Autowired.如果希望按照名称进行匹配,并且不需要支持@Primary注解,可以选择@Resource;如果希望按照类型进行匹配,并且需要支持@Primary注解,可以选择@Autowried.根据具体情况选择合适的注解来实现自动装配
到此这篇关于深入了解Spring中的@Autowired和@Resource注解的文章就介绍到这了,更多相关Spring @Autowired和@Resource内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: 深入了解Spring中的@Autowired和@Resource注解
本文链接: https://www.lsjlt.com/news/210648.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0