zoukankan      html  css  js  c++  java
  • @Resource学习笔记

    @Resource 和 @Autowired 一样,是用来实现依赖注入的。

    声明一个接口

    public interface UserService {
        void readyTest(String var);
    }
    

    单个实现类

    新建一个类,实现该接口

    import org.springframework.stereotype.Service;
    
    @Service
    public class UserServiceImpl implements UserService{
        @Override
        public void readyTest(String var) {
            System.out.println("方法被调用,收到参数:"+var);
        }
    }
    

    使用@Resource 注解,实现属性的自动装配

    @SpringBootTest
    class TestApplicationTests {
    
        @Resource
        UserService userService;
    
        @Test
        void contextLoads() {
            userService.readyTest("Resource");
        }
    
    }
    

    多个实现类

    我们新建一个实现类

    import org.springframework.stereotype.Service;
    
    @Service
    public class UserServiceNewImpl implements UserService{
        @Override
        public void readyTest(String var) {
            System.out.println("新方法被调用,收到参数:"+var);
        }
    }
    

    当有多个实现类的情况下,会报错:org.springframework.beans.factory.BeanCreationException: Error creating bean with name

    需要区分的是,idea不会自动识别此错误,在运行时才会报错。

    解决方法就是手动指定@Resource的name属性:

    @SpringBootTest
    class TestApplicationTests {
    
        @Resource(name = "userServiceNewImpl")
        UserService userService;
    
        @Test
        void contextLoads() {
            userService.readyTest("Resource");
        }
    
    }
    

    本文来自博客园,作者:Bin_x,转载请注明原文链接:https://www.cnblogs.com/Bin-x/p/15458476.html

  • 相关阅读:
    [LeetCode#252] Meeting Rooms
    [LeetCode#247] Strobogrammatic Number II
    [LeetCode#265] Paint House II
    [LeetCode#256] Paint House
    [LeetCode#279] Perfect Squares
    [LeetCode#259] 3Sum Smaller
    [LeetCode#261] Graph Valid Tree
    [LeetCode#271] Encode and Decode Strings
    xfsdump的选项-L和-M
    Centos7 报错welcome to emergency mode
  • 原文地址:https://www.cnblogs.com/Bin-x/p/15458476.html
Copyright © 2011-2022 走看看