springboot动态获取接口的实现类

在Spring Boot项目里,当一个接口存在多个实现类时,需要动态获取这些实现类,文中将直接给出相关代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  •           在springboot 的项目中,如果一个接口有多个实现类,我们需要动态获取,直接上代码;

 

@RestController
public class PersonController {

    @Resource(name="${active}")
    private HelloService helloService;

    @RequestMapping("/test")
    public String get() {
        return helloService.getName();
    }

}
public interface HelloService {

    String getName();

}



@Service("hello1")
public class HelloServiceImpl1  implements HelloService {
    @Override
    public String getName() {
        return "111";
    }
}



@Service("hello2")
public class HelloServiceImpl2 implements HelloService {

    @Override
    public String getName() {
        return "222";
    }
}

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);

    }
}

 

### 使用 `getBean` 方法获取 Spring Boot 中的具体实现类 在 Spring Boot 应用程序中,可以利用 `ApplicationContext` 的 `getBean()` 方法来获取由 Spring 容器管理的 bean 实例。当存在多个相同类型的 bean 时,可以通过指定名称或使用限定符(Qualifier)来精确匹配所需的实现类。 #### 基于类型获取 Bean 如果只有一个特定类型的 bean,则可以直接按照该类型请求它: ```java @Autowired private ApplicationContext context; public void someMethod(){ MyInterface myImpl = (MyInterface)context.getBean(MyInterface.class); } ``` 这种方式适用于单一实现的情况[^1]。 #### 按照名字和类型组合查找 Bean 如果有多个实现了同一接口的不同类,并希望从中选出某一个作为目标对象的话,那么应该提供更详细的参数给到 `getBean()` 函数: ```java @Autowired private ApplicationContext context; public void anotherMethod(){ String beanName = "specificImplementation"; // 这里填写想要获得的那个bean的名字 SpecificImplementation specificInstance = (SpecificImplementation)context.getBean(beanName, SpecificImplementation.class); } ``` 这里不仅指定了要找的对象所属的数据结构形式——即它的 Java 类型;同时也给出了这个对象在整个应用程序范围内独一无二的身份标识——也就是所谓的 “bean name”。这使得即使有好几个候选者都符合所给定的形式条件,也能够准确无误地定位到唯一的一个实例上去[^2]。 #### 利用 @Primary 或 @Qualifier 来简化注入逻辑 为了减少硬编码字符串带来的风险以及提高代码可读性和维护性,在配置文件或者注解处标记好优先级较高的默认选项(`@Primary`)或是自定义标签(`@Qualifier`)不失为一种明智的选择。 例如: ```java @Service @Primary public class DefaultServiceImpl implements ServiceInterface { } @Service("customService") public class CustomServiceImpl implements ServiceInterface{ } ``` 此时再尝试通过 `getBean(ServiceInterface.class)` 就只会返回被标注成主要服务端口的那个版本了;而对于后者而言则需显式给出别名才能成功检索出来。 ```java @Autowired private ApplicationContext ctx; @Test void testGetBeansWithAnnotation() throws Exception { ServiceInterface defaultService = ctx.getBean(ServiceInterface.class); assertEquals(DefaultServiceImpl.class, defaultService.getClass()); ServiceInterface customService = ctx.getBean("customService", ServiceInterface.class); assertEquals(CustomServiceImpl.class, customService.getClass()); } ``` 以上就是几种常见的方式用来从 Spring 上下文中提取出确切的服务层组件实体[^3]。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值