Похожие чаты

I have a module which contains an interface, and i

have a default implementation for this interface in that module


As well i have another module which implements this interface but but it's annotated with @Primary

currently i need to create a third module, but overide the implementation that is annotated with @Primary

any suggestions?

3 ответов

7 просмотров

——————— summary: - better use "autoconfiguration" approach for defining "default if not overridden" kind of beans - if not applicable, otherwise use qualifiers/bean names to specify which exactly bean impl you want - if not applicable, otherwise configure beans autoscanning/importing - otherwise try bean/bean factory post processors to replace one bean impl with other

Since you didn't gave any details for my previous question for clarification, then I'll give you generic advices. Assume that you have 3rd partly lib "some-spring-lib", then your library you have control over called "lib-a", same type "lib-b" that depends on "lib-a", and finally the spring application "spring-app". Suggestions: - rule of thumb - never ever use @Primary in libraries, use it ONLY in applications, in your case, this is "spring-app"; this is because spring doesn't have @Secondary annotation (which designers of spring realized and added it when they designed micronaut), and as soon as you introduce "Primary" in your code, you'll mark some ipmlementation as of highest priority; thus you have to do this only in that place which is known to be not re-used in some other context where the requirements may change - if you have multiple beans of same type, you may consider using qualifiers (https://www.baeldung.com/spring-qualifier-annotation); this works best when you have multiple implementations of equal importance, which should be used at the same time in different places; example - imagine you have multiple "Cache" beans, each of which is an api for working with cached entities of different type, let's say you have "Cache of users" and "Cache of roles", "Cache of books", etc., and in one place of your code you need "Cache of users", while in other place you need "Cache of books"; qualifiers work best here, they are designed exactly for such situation, it's all about semantics (based on your question, qualifiers won't fit you) - also you can use another form of qualifiers - "named" beans, i.e. autowire/inject beans with specifying specific name of the bean (https://www.baeldung.com/spring-bean-names); the semantics and area of applicability is the same as in qualifiers; it just has different advantage/tradeoff balance - it's simpler to use, but bean names are strings which are subject to typos, and those names may become a mess in big system with many shared libraries - if you're designing shared library with spring beans, which should be "default, used uless client didn't specify anything else" principle, then check out how spring boot ecosystem does it - it has concept of "autoconfiguration" (https://www.baeldung.com/spring-boot-custom-auto-configuration), it does exactly what you seem to be doing; it's very clumsy in iplementing to be honest, but it's very easy to use when you applied it ; so in my example "some-spring-lib" uses exactly this approach, it defines beans and declares factory methods for those beans with lots of usage of @ConditionalOn... to make them overridable by users; I recommend you to use this approach as it's the most elegant and easy to use as a client of the library, but it may be not an option for you depending on the semantics of those beans; just use @ConditionalOnClass/@ConditionalOnMissingClass correctly - exclude offending beans/spring-configurations from autoscanning (https://www.baeldung.com/spring-component-scanning), or the opposite - include only specific bean with @Import(https://www.baeldung.com/spring-import-annotation ); this is not very reliable option, and is ok to be applied in end applications ("spring-app" in our example), but not in libraries - another option would be to replace beans with "BeanPostProcessor" or "BeanFactoryPostProcessor"; this is very bad and dirty solution and generally should be used for other purposes; this may be an option only when you don't have control any control over "lib-a" and "lib-b" source code, and those have obvious unresolvable conflict; so you can add bean post processor, or bean factory post-processor either in "lib-b" or in "spring-app" which takes winning "Primary" bean and replaces it with new instance of other implementation you want (yak, clumsy)

Похожие вопросы

Обсуждают сегодня

Всем привет, написал код ниже, но он выдает сегфолт, в чем причина? #include <stdio.h> #include <stdlib.h> #include <string.h> struct product { char *name; float price; };...
buzz базз
60
Хотел бы спросить у знающих, правильную ли я выбрал книгу для начала изучения ассемблера Юрова В.И ? Или есть более лучшие книги для начала обучения?
Botsman
25
Добрый день, не подскажите, если в OC-V3 поменять страндартную директорию /storage/ на /storage2/ - не будет сильно много проблем ?
Max Dubovsky
32
Conversation at a festival with a non-crpto person (not a normie by any stretch, though): * person: tell me about crypto, me: ok, the original idea is p2p sound money for the...
molecular#123 🐓
25
Книга Юрова В.И пойдёт для обучения?
Botsman
24
$params = [ 'formid' => 'feedbackForm', 'formTpl' => '@CODE: <form class="form-validate" data-id="ajax_form"> <fieldset class="margin-bottom-md"> ...
Pathologic
1
> Примечательно, что новый владелец удаляет из GitHub любые жалобы, указывающие на подозрительную активность или смену владельца, и, видимо, рассчитывает на то, что пользовате...
Alex Sherbakov
1
Today, DENT achieved a significant step forward in DENTX adoption 🥳 Getting DENTX and starting staking is much easier: DENTX is available on Uniswap! Everyone can swap their ...
Thomas
3
I bought some PHA tokens on Kucoin, which is the best wallet to store and easy to use?
AMR
19
Hey there Which is the best Linux destro for developers (coding)? To my research on reddit, they said Linux mint is good for mid level spec and Ubuntu for high Lev hardwar...
Wiz 🪄
11
Карта сайта