I use the Unbound ID library that has a class LDAPConnection which has no default constructor and which implements LDAPInterface. I produce the LDAPConnection as follows:
@Produces
@SimpleLdapConnection
@ApplicationScoped
public LDAPInterface createLdapConnection() throws GeneralSecurityException, LDAPException {
LDAPConnection conn = new LDAPConnection(host, port, username, password);
return conn;
}
I now want to inject this LDAPConnection class to a second producer, which should generate a Connection Pool:
@Inject
@SimpleLdapConnection
LDAPInterface simpleLdapConnection;
@Produces
@Default
@ApplicationScoped
public LDAPInterface produceLdapConnectionPool() throws GeneralSecurityException, LDAPException {
LDAPConnectionPool pool = new LDAPConnectionPool((LDAPConnection)simpleLdapConnection.g, connectionPoolInitialSize, connectionPoolMaxSize);
return pool;
}
To create the LDAPConnectionPool, I need to cast the simpleLdapConnection to an LDAPConnection (as it must be an LDAPConnection).
However, I get the error:
java.lang.ClassCastException: org.jboss.weld.proxies.LDAPInterface$1687649628$Proxy$_$$_WeldClientProxy cannot be cast to com.unboundid.ldap.sdk.LDAPConnection
at at.rsg.lp.benutzerverwaltung.business.repository.LdapConnectionPoolProvider.produceLdapConnectionPool(LdapConnectionPoolProvider.java:59)
How can I get around this error? P.S. changing the first producer to return an LDAPConnection does not work as I get the error "Injected normal scoped bean is not proxyable".
What you are running into, from CDI point of view, are the defined bean types of a producer method. This is backed by CDI specification.
In short, for producer methods, the bean types are derived from return types and the interfaces it implements. E.g. the actual implementation type is not included. The reason for that is exactly what you see when you saw when you tried to return the actual implementation type - impls often contain final
methods or other bumps making them unproxyable.
There are two things I can think of to solve this:
@Typed
annotation on your producer - I doubt it will work in this case, but it could be worth a shot. This annotation declares all the types the bean will have. You would use it like this - @Typed({LDAPInterface, LDAPConnection})
.