• @Resource和@Autowired的区别


    经常我们会碰到有人注入使用@Resource,有人使用@Autowired,这里简单明了地总结一下两者的区别。

    首先最大的区别,@Resource是Java提供的注解,而**@Autowired**则是Spring提供的注解:

    @Resource
    import javax.annotation.Resource;
    @Autowired
    import org.springframework.beans.factory.annotation.Autowired;
    

    其次,两者自动注入查找的方式也不一样:

    • @Resource先按照byName去找,如果没有则会按照byType去找。当然,一旦你如果设置了name属性,那它只会根据byName去找,找不到就直接报错了。
    • @Autowired顺序相反,先按照byType去找,如果没有则按照byName去找。

    最后应用场景和性能不一样:

    @Autowired效率比较低,@Resource效率较高。

    当接口只有一个实体类实例的时候,两者都差不多,但是当接口的实例超过1个的时候,我们需要根据名字去指定加载的接口实例的时候,使用**@Resource(name = “xxxx”')要比@Autowired组合@Qualifier**效率高很多…

    举例:此时存在接口PersonService,但它存在两个实例ManSeviceImplWomanServiceImpl,我们就可以使用@Resource来指定接口实现的名字,从而保证注入的对应实例是我们需要的:

    PersonService:

    public interface PersonService {
        String run();
    }
    

    ManServiceImpl:

    @Service("manService")
    public class ManServiceImpl implements PersonService{
        @Override
        public String run() {
            return "man running...";
        }
    }
    

    WomanServiceImpl:

    @Service("womanService")
    public class WomanServiceImpl implements PersonService{
        @Override
        public String run() {
            return "woman running...";
        }
    }
    

    定义PersonController进行测试:

    @RestController
    public class PersonController {
        @Resource(name = "manService")
        private PersonService personService;
    
        @GetMapping("/person")
        public String testPerson() {
            return personService.run();
        }
    }
    

    postman测试结果:

    image-20220921200831349.png

  • 相关阅读:
    js-hodgepodge 一个全面的JS工具库
    CameraServiceProxy启动-Android12
    对C语言符号的一些冷门知识运用的剖析和总结
    Java 24 Design Pattern 之 观察者模式
    直销系统开发是找开发公司还是外包团队?
    通用大模型时代教育面临的机遇与挑战
    算法基础-数学知识-容斥原理、博弈论
    在Visual Studio Code中安装JetBrains Mono字体
    树和二叉树的概念与使用(Tree&Binary Tree)
    单目标追踪——【相关滤波】框架
  • 原文地址:https://blog.csdn.net/SmallPig_Code/article/details/127095428