Hi,
I'm trying to implement a simple type conversion framework in CDI. Typically,
you can either implement the TypeConverter interface or annotate some methods
in your beans:
public interface TypeConverter<S, T> {
T convert(S source);
}
public class StringToIntegerTypeConverter implements TypeConverter<String,
Integer> { ... }
public class StringToLongTypeConverter implements TypeConverter<String, Long> {
... }
public MyConverters {
@Converts public Integer stringToInteger(String value) { ... }
@Converts public Long stringToLong(String value) { ... }
}
A specific Extension "bridges" the annotated methods to a full TypeConverter (a
custom Bean<?> is registered with an API types of ParameterizedTypeImpl(rawType
= TypeConverter.class, ownerType = null, actualTypeArguments =
[method.getGenericParameterType[0], method.getGenericReturnType])).
Then a TypeConversionService is responsible to find the adequate Converter
through the BeanManager and call it with the provided object to be converted.
public class TypeConversionService {
public <T> T convert(Class<T> targetType, Object source) { ... }
public <T> T convert(TypeLiteral<T> targetTypeLiteral, Object source) { ... }
}
My problem is the following: as soon as 2 or more TypeConverters are present in
the module (let's say StringToIntegerTypeConverter and
StringToLongTypeConverter), an ambiguous dependency exception is thrown.
For example:
public class MyBean {
@Inject TypeConverter<String, Integer> stringToIntegerTypeConverter;
@Inject TypeConverter<String, Long> stringToLongTypeConverter;
// won't work
}
If I delete one of the TypeConverter classes (StringToLongTypeConverter for
example), the remaining TypeConverter (StringToIntegerTypeConverter) is
injected at the 2 injection points (stringToIntegerTypeConverter=ok and
stringToLongTypeConverter=!ok).
Is it possible with CDI to have such a scenario without using additional
qualifiers to qualify each converter and only rely on the (parameterized) type
information to tell them apart?
I've seen some discussions on StackOverflow saying the TypeConverter should
belong to the Dependent scope but it didn't work for me.
Thanks,
Xavier