如果一个接口有多个实现类,@Autowired 时会发生什么?如何解决?

从零开始:如何用大语言模型构建你的第一个路径规划智能体 本文详细介绍了如何利用大语言模型(LLM)构建路径规划智能体,从基础概念到实战案例,涵盖TSP和CVRP问题的解决方案。通过选择合适的LLM模型、设计有效的提示工程和实现自我验证,即使没有运筹学背景也能快速上手。文章还提供了部署与优化智能体的实用技巧,帮助读者在物流配送、机器人导航等领域应用这一技术。 阅读详情

当一个接口有多个实现类,并且都注册为 Spring Bean 时,直接使用 @Autowired 注入该接口类型,Spring 会“感到困惑”。

会发生什么?

Spring 在进行依赖注入时,首先会按类型查找。它会发现有多个 Bean(EmailNotificationService 和 SmsNotificationService)都匹配 NotificationService 这个类型。

此时,Spring 不知道该注入哪一个,于是会抛出异常:

org.springframework.beans.factory.NoUniqueBeanDefinitionException

这个异常信息非常直白:“找到了多个符合条件的 Bean,但我不知道你要哪一个”。

让我们用一个具体的例子来说明:

// 1. 接口
public interface NotificationService {
    void send(String message);
}

// 2. 实现类 A
@Service
public class EmailNotificationService implements NotificationService {
    @Override
    public void send(String message) {
        System.out.println("通过邮件发送通知: " + message);
    }
}

// 3. 实现类 B
@Service
public class SmsNotificationService implements NotificationService {
    @Override
    public void send(String message) {
        System.out.println("通过短信发送通知: " + message);
    }
}

// 4. 使用者 (会出错!)
@Service
public class OrderService {
    @Autowired
    private NotificationService notificationService; // Spring: ??? 该注入 Email 还是 SMS?

    public void placeOrder() {
        // ...下单逻辑...
        notificationService.send("您的订单已创建!");
    }
}

在启动时,Spring 容器会因为无法为 OrderService 找到一个唯一的 NotificationService Bean 而失败。


如何解决?

有多种优雅的方式可以解决这个问题,具体取决于你的业务意图。

解决方案 1:使用 @Primary - 指定一个首选的实现

如果你希望在大多数情况下都使用某一个特定的实现(比如,邮件是默认的通知方式),你可以将它标记为 首选(Primary)。

@Service
@Primary // <-- 加上这个注解
public class EmailNotificationService implements NotificationService {
    // ...
}

工作原理:当 Spring 发现有多个候选 Bean 时,它会优先选择被 @Primary 注解的那个。这样,OrderService 中的 @Autowired 就会成功注入 EmailNotificationService 的实例。

优点:简单明了,消费者(OrderService)的代码无需任何改动。
适用场景:当多个实现中有一个是“默认”或“主要”选项时。

解决方案 2:使用 @Qualifier - 精准指定要注入的 Bean

如果你想在注入点明确指定使用哪一个实现,可以使用 @Qualifier 注解。这就像是按“名字”来查找。

首先,你需要知道 Bean 的名字。默认情况下,Spring Bean 的名字是其类名的小驼峰形式(e.g., EmailNotificationService 的 Bean 名是 emailNotificationService)。

// 使用者
@Service
public class OrderService {
    
    private final NotificationService notificationService;

    // 在构造函数或字段上使用 @Qualifier
    @Autowired
    public OrderService(@Qualifier("smsNotificationService") NotificationService notificationService) {
        this.notificationService = notificationService;
    }

    public void placeOrder() {
        // ...下单逻辑...
        notificationService.send("您的订单已创建!"); // 这里会使用短信服务
    }
}

你也可以在实现类上用 @Qualifier 自定义一个名字,然后在注入点使用它:

@Service
@Qualifier("emailNotifier") // 自定义一个名字
public class EmailNotificationService implements NotificationService { ... }

// 注入时使用自定义的名字
@Autowired
@Qualifier("emailNotifier")
private NotificationService notificationService;

优点:非常精确,控制权在消费者手中,可以灵活选择任意一个实现。
适用场景:当消费者需要一个特定的、非默认的实现时,或者没有明确的默认实现时。

解决方案 3:注入所有实现类的集合

有时候,你的业务需求可能是“向所有渠道发送通知”。在这种情况下,你可以直接注入一个包含所有 NotificationService 实现的 List 或 Map。

A. 注入 List

@Service
public class NotificationManager {
    
    private final List<NotificationService> notificationServices;

    @Autowired
    public NotificationManager(List<NotificationService> notificationServices) {
        this.notificationServices = notificationServices;
    }

    public void notifyAllChannels(String message) {
        // Spring会自动将所有NotificationService的Bean注入这个List
        for (NotificationService service : notificationServices) {
            service.send(message);
        }
    }
}

// 调用时会输出:
// 通过邮件发送通知: 您的订单已创建!
// 通过短信发送通知: 您的订单已创建!

B. 注入 Map
如果你还想通过 Bean 的名字来获取特定的实现,可以注入一个 Map<String, NotificationService>。

@Service
public class NotificationManager {

    private final Map<String, NotificationService> serviceMap;

    @Autowired
    public NotificationManager(Map<String, NotificationService> serviceMap) {
        this.serviceMap = serviceMap; // key是Bean的名字, value是Bean实例
    }

    public void sendByChannel(String channelName, String message) {
        NotificationService service = serviceMap.get(channelName);
        if (service != null) {
            service.send(message);
        } else {
            System.out.println("未找到渠道: " + channelName);
        }
    }
}

// 调用
// notificationManager.sendByChannel("smsNotificationService", "请注意查收");

优点:非常强大和灵活,是**策略模式(Strategy Pattern)**的完美实现。
适用场景:当你需要执行所有实现,或者需要根据某些条件动态选择一个实现时。

总结与最佳实践

解决方案核心思想优点适用场景
@Primary“默认选项”消费者代码无感知,配置简单多个实现中有一个是明确的“首选”或“默认”
@Qualifier“按名指定”精确,消费者可以灵活选择消费者需要特定实现,或没有默认实现时
注入集合 List/Map“我全都要”极度灵活,完美支持策略模式需要执行所有实现,或需要动态选择策略时

最佳实践建议:

  • 优先使用构造函数注入:它能保证依赖在对象创建时就是可用的,并且方便进行单元测试。
  • 如果有一个明确的通用实现,使用 @Primary 是最干净的方案。
  • 如果不同的消费者需要不同的实现,@Qualifier 是你的不二之选。
  • 当你需要构建一个可扩展的系统(比如,未来可能增加 App 推送、微信通知等),注入集合的方式是最高级、最灵活的设计。
基于单片机的按键加1数码管显示(仿真+程序)5046 1、51+Proteus8.10;2、学习计数统计、数码管显示驱动; 阅读详情

相关推荐

Cloudflare 5秒盾逆向实战:13次请求背后的Python补环境框架搭建指南

本文深入解析了如何通过Python构建浏览器环境模拟框架,以应对Cloudflare 5秒盾等现代Web防护机制。文章详细拆解了其背后复杂的13次请求链,涵盖了JavaScript执行引擎集成、DOM事件模拟、网络请求控制及Canvas指纹等环境检测的完整实现方案,为自动化数据采集和逆向工程提供了实战指南。

gold的博客 347

接口存在多个实现类时的动态调用

文章目录问题的提出实例 版权声明:本文为优快云博主「EmineWang」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.youkuaiyun.com/a718515028/article/details/72457436 问题的提出 在实际工作中,我们经常会遇到一个接口及多个实现类的情况,并且在不同的条件下会使用不同的实现类。从使用方式上看,有些类似SPI的用法, 但是由于SPI的使用并不是太方便,那么怎么办呢?我们可以借助Application

qq_40419080的博客 2677

问题:dpkg-deb: error: paste subprocess was killed by signal (Broken pipe)

 1. 问题:Ubuntu安装软件的过程中出现依赖项的问题 “E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).” 按照指示执行如下两条命令都没有解决问题。 sudo apt-get -f install sudo apt-get --fix-broken ...

gloria_littlechi的博客 2万+

一个接口有多个实现,调用时的解决方案

假如一个接口有两个实现类。在实现类上取名字 @Service("developservice") public void DevelopEmployeeServiceImpl implements EmployeeService { public EmployeeDto getEmployeeById(Long id) { ... // 业务代码 } } @Service("testservice") public void TestEmployeeServiceImpl

weixin_45335305的博客 1009

从零搭建私有AI工作站:Ollama+DeepSeek+Dify本地化部署全攻略

本文提供了一份详尽的本地化AI工作站搭建指南,核心在于实现数据安全与离线可用。通过整合Ollama、DeepSeek与Dify三大工具,手把手教你完成从环境配置、模型部署到可视化应用构建的全过程,重点解决了Dify连接Ollama等关键步骤,助你打造一个完全自主可控的私有AI开发环境。

weixin_28396629的博客 311

DC-DC BUCK电路 PCB 布局布线 5 要点:以 XL4015 12V转5V 为例解析噪声控制

本文以XL4015 12V转5V降压电路为例,详细解析DC-DC BUCK电路PCB布局布线的5个关键要点,重点探讨噪声控制策略。通过功率回路最小化、热管理与接地优化、电感电容布局、反馈网络防干扰设计以及实测验证技巧,帮助工程师实现高效稳定的电源设计,显著降低输出纹波和电磁干扰。

weixin_29165725的博客 369

一个接口有多个实现类时,调用接口时,如何判定调用的哪个实现类?

一个接口有多个实现类时,调用接口时,如何判定调用的哪个实现类?这里有三种方法解决

Binary_huang的简介 7161

【GEE实战指南】Python本地API配置避坑与一站式环境搭建

本文详细介绍了Google Earth Engine(GEE)Python本地API的配置避坑指南与一站式环境搭建流程。通过conda创建隔离环境、账户认证关键步骤、初始化代码的正确写法以及实战测试案例,帮助开发者快速掌握GEE Python API的配置技巧,避免常见错误,提升地理空间数据分析效率。

weixin_42624889的博客 186

@Autowired一个接口有多个实现类

之前用到@Autowired这个注解的时候,总是纳闷 public class B implements A; public class C implements A; @Autowired private A a; 此时a调用方法是调用B的方法还是C的方法,实测如此启动会报错抛出了org.springframework.beans.factory.BeanCreationException,而...

qq_37752382的博客 3525

28、基于图像快速序列视觉呈现(RSVP)的脑机接口特征提取与分类算法综述

本文综述了基于图像快速序列视觉呈现(RSVP)的脑机接口(BCI)中的特征提取与分类算法。RSVP技术通过快速连续呈现图像序列,结合脑电图(EEG)信号分析,实现对目标图像的识别和标记。文章详细介绍了RSVP实验的设计、EEG数据的采集与预处理,并探讨了低信噪比、维度灾难、重叠epoch和不平衡数据集等挑战。针对特征提取,讨论了有监督空间滤波方法(如CSP、xDAWN、LDA波束形成器)的原理和应用。在分类策略部分,涵盖了线性分类技术(如LDA、BLR、LR、SVM)和非线性分类方法(如MLP、CNN)。文

hh234的博客 336

基于YOLOv10的机器人抓取引导系统:从物体检测到精准抓取

python# 数据标注工具简化版import os"""启动标注工具""""""标注单张图像"""print(f"标注图像: {os.path.basename(img_path)}")print("请在图像上绘制抓取矩形框...")# 这里应该实现交互式标注界面# 简化版本直接返回示例标注# 示例标注数据"""保存标注结果"""# 保存为YOLO格式# 转换为YOLO格式。

YOLO 377

Spring一个接口多个实现类,一个实现类实现多个接口,注入方法

1、一个实现类实现多个接口 例如:serviceImpl implements Interface1,Interface2 在controller中 @AutowiredInterface1 只能调用Interface1接口的方法 总结,注入单个接口,只能调用对应的接口方法 2、一个接口多个实现类,注入指定的实现类 例如:Interface 接口有两个实现类 Interfac...

k849875005的博客 2万+

元数据治理实战:构建企业数据地图与血缘体系

元数据(Metadata)是描述数据的数据,是你能了解“数据是怎么来的”、“它是做什么的”、“能不能用”的基础信息。📌 举个例子:order_idstringods_order定义:平台内用户在订单系统中产生的唯一订单编号更新时间:每天凌晨 2 点,由 Airflow 调度任务生成所属人:张三(数据开发部)🔍 这些信息本身不直接参与计算,但它们是数据可管理、可追踪、可评估的基础。模块实战建议元数据类型技术 + 业务 + 操作元数据三类统一治理治理路径。

晴天彩虹雨的博客 290

如何使用@Autowired注入含有多个实现类的接口

一、问题描述 在spring的注解使用中,@Autowired注解的作用是注入bean,但是假如有一个接口,它包含两个实现类,这个时候应该怎么实现注入呢? 二、单个实现类使用情况 controller: @RestController @RequestMapping(value = "/user") public class UserController { @Autowired private IUserService iUserService ; @Reque

bird_tp的博客 1万+

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Spring注入的是接口还是实现类,@Autowired注入对象接口和实现类的区别,同一接口有多个实现类如何注入(转)

问题 为什么xxxController注入的是xxxService,而不是xxxServiceImpl? controller---->service接口 表面注入的是接口,实际注入的是实现类对象(实现类唯一)。 controller---->serviceImpl实现类 可以对实现类增强,如事务、日志等(AOP动态代理实现)。 结论 @Autowired的对象是通过接口的话,Spring默认会使用jdk动态代理,jdk动态代理只能对实现了接口的类生成代理,而不能针对类,而且还可以对实现类

JAVA行者 9457

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

【Spring】一个接口有多个实现类,如何指定一个实现类?@Resource、@Autowired、@Qualifier

如果一个接口有2个不同的实现, 那么怎么来Autowire一个指定的实现? 举个例子: 1、接口:ILayer public Interface ILayer{ ...... } 2、实现类:ImageLayerImpl ,实现了ILayer接口。 @Service("imageLayerImpl") public class ImageLayerImpl impliment...

Mr_EvanChen的Blog 6463

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

spring注入接口还是实现类,同一接口有多个实现类,如何注入

1、接口:IUserService public interface IUserService { public void sayHello(); } 2、实现类:UserServiceImpl,实现了UserService接口 @Service("UserServiceImpl ") public class UserServiceImpl implements IUser...

q503385724的博客 1万+

一个接口有多个实现类的调用方式

场景: A用户调用Aservice实现类,B用户调用Bservice实现类 1、使用switch-case public static Person printPerson(int kind) { Person p = null; switch (kind) { case FIRST: p = new A(&quot;人1&quot;);break; case SECOND...

u012804909的专栏 7836

同一接口有多个实现类,怎么来注入一个指定的实现?@Resource、@Autowired、@Qualifier

如果一个接口有2个不同的实现, 那么怎么来Autowire一个指定的实现? 举个例子: 1、接口:ILayer public Interface ILayer{ ...... } 2、实现类:ImageLayerImpl ,实现了ILayer接口。 @Service("imageLayerImpl") public class ImageLayerImpl implimen...

二十同学 8万+

autowire加载指定实现类_如何使用@Autowired注入含有多个实现类的接口

一、问题描述在spring的注解使用中,@Autowired注解的作用是注入bean,但是假如有一个接口,它包含两个实现类,这个时候应该怎么实现注入呢?二、单个实现类使用情况controller:@RestController@RequestMapping(value = "/user")public class UserController {@Autowiredprivate IUserSer...

weixin_42503069的博客 4474

@Autowired一个有多个实现类的接口

@Autowired一个接口的时候不少人都会有疑惑,如果 public class B implements A; public class C implements A; @Autowired private A a; 此时a调用方法是调用B的方法还是C的方法呢?实测如此操作会导致启动报错了org.springframework.beans.factory.BeanCreationException,而原因是注入的时候发现有2个匹配的bean,(这个注解的首先是通过byType的方式注入Bean)

yilongchuan的博客 1655

一个接口多个实现类,controller层如何操作

今天,写代码时,突发奇想,每次写Service层时 都是一个接口对应一个实现类,如果有多个实现类实现同一个接口,那么在Controller层中,注入后调用,咋知道到用的是哪个接口的方法,经过一番测试,和查找资料,终于找到了结果: 一个接口多个实现类,需注入指定的实现类 例如:Interface 接口有两个实现类 InterfaceImpl1 和 InterfaceImpl2 //实现类1 @Service public class InterfaceImpl1 implements Interface

北冥的博客 2692

同一个接口有两个或两个以上实现类时,如何注入

如果有一个接口,但有多个实现类,应如何注入? 例,有一个TestService接口,代码如下: public interface TestService { void run(); } 此时有两个实现类实现了这个接口。 实现类一: @Service("TestServiceImpl") public class TestServiceImpl implements TestService { @Override public void run() { System.out.println

博客 7006

autowire加载指定实现类_【Spring】一个接口有多个实现类,如何指定一个实现类?@Resource、@Autowired、@Qualifier...

https://blog.youkuaiyun.com/qq_18298439/article/details/89175439如果一个接口有2个不同的实现, 那么怎么来Autowire一个指定的实现?举个例子:1、接口:ILayerpublic Interface ILayer{......}2、实现类:ImageLayerImpl ,实现了ILayer接口。@Service("imageLayerImpl...

weixin_39546501的博客 2496

@Autowired按照类型一次将同一接口的多个实现类注入的方法

@Autowired注解一次将同一接口的多个实现类全部注入,只需要在注入时以List/Map形式定义要注入的接口即可。 /** * 定义接口 */ public interface LoginService { void sout(); } /** * 实现类LoginServiceAImpl */ @Service public class LoginServiceAImp...

清风 3221
上一篇: 在 Web 环境中,request、session、application 这些作用域是做什么的?
下一篇: 面试官:Spring 如何控制 Bean 的加载顺序?
冰糖心书房
博客等级 码龄15年 6014粉丝 690原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

冰糖心书房

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值