i have integration tests supposed mock out 1 of many beans in system. this, have @configuration looks this:
@configuration public class mockcontext { @primary @bean public realbean realbean() { return new mockbean(); } } i noticed method gets used if realbean java class without @component. if realbean is @component, have change context method this:
@configuration public class mockcontext { @primary @bean public realbean getrealbean() { return new mockbean(); } } can explain why need change method name , can find these rules? takes long time troubleshoot these "why isn't mockcontext working correctly?" issues.
fwiw, here's how i'm using context in test:
@runwith(springjunit4classrunner.class) @springapplicationconfiguration(classes = {realcontext.class, mockcontext.class}) @webappconfiguration public abstract class abstractintegrationtest { and integration test extend class. using spring boot 1.2.4.release
you can have various beans registered same type. need have different names.
if use @bean annotation without name attribute, name of bean extracted method name (in case realbean/getrealbean).
when use @component annotation without attribute (which specifies bean name), name of bean extracted method name first letter lowercased.
so first case, name clash. can't have 2 beans named realbean.
your second example without clash because bean annotated @component has name realbean , second bean registered via @bean has name getrealbean.
@primary annotation helps spring choose bean pick if there 2 of same type , inject type. when inject name (usage of @qualifier annotation), can inject secondary instance.
Comments
Post a Comment