0

Is there a way to change the value passed to a custom @Qualifier, and pass it to the delegating @Qualifier?

I understand that we can create custom qualifiers by

@Qualifier
@Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface Van {
    String value() default "";
}

And the following would pass the value "green" to @Qualifier and autowire a Vehicle bean named "green".

@Autowired
@Van("green")
Vehicle vehicle;

Let's say I have Vehicle beans created with names "greenVehicle" and "redVehicle".

Is there a way to format the value passed into @Van("green") and autowire the "greenVehicle" Vehicle bean, i.e having @Qualifier("greenVehicle") behind the scene?

1 Answer 1

1

Assume you have interface

public interface Vehicle {

    // some methods

}

and its implementation

public class VehicleImpl implements Vehicle {

    // some methods impl

}

Your custom qualifier should be

@Qualifier
@Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface Van {

    @AliasFor(annotation = Qualifier.class, attribute = "value")
    String value() default "";

}

Then you can create Vehicle beans like:

@Bean("green")
Vehicle vehicle() {
    return new VehicleImpl();
}

or like:

@Bean
Vehicle green() {
    return new VehicleImpl();
}

and autowire as you expected:

@Van("green")
@Autowired
Vehicle vehicle;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! The issue I'm facing is I'm creating the "greenVehicle" and "redVehicle" beans programmatically. So I need a way to convert @Van("green") into @Qualifier("greenVehicle"), in order to autowire the correct bean.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.