Error while setting targetConnectionFactory in UserCredentialsConnectionFactoryAdapter Spring 4

1.9k views Asked by At

We are receiving a compilation error in the following code, while trying to set the targetConnectionFactory.

According to the example given in Spring 4 documentation for UserCredentialsConnectionFactoryAdapter, the setTargetConnectionFactory() method takes the object of JndiObjectFactoryBean as an argument. But, looks like the JndiObjectFactoryBean hasn't implemented the 'ConnectionFactory' interface, which is supposed to be the argument of this set method.

Is this any bug with Spring 4 ? if JndiObjectFactoryBean object cannot be set as targetConnectionFactory , then what can be used in it's place ?

JndiObjectFactoryBean theJndiObjectFactoryBean = new JndiObjectFactoryBean();
theJndiObjectFactoryBean.setJndiTemplate(getJNDITemplate());
theJndiObjectFactoryBean.setJndiName(jndiConnectionFactoryName);
UserCredentialsConnectionFactoryAdapter theUserCredentialsConnectionFactoryAdapter = new UserCredentialsConnectionFactoryAdapter();
theUserCredentialsConnectionFactoryAdapter.setTargetConnectionFactory(theJndiObjectFactoryBean);
2

There are 2 answers

4
jst On BEST ANSWER

The big difference between your code and the example is in the XML config example that myTargetConnectionFactory is actually a bean managed by Spring. You aren't doing that. You are just creating a new object Spring doesn't know about. The magic happens when setting the targetConnectionFactory of myConnectionFactory. Even though it looks like the type if JndiObjectFactoryBean, Spring is actually injecting the underlying connectionFactory created by the factory bean.

The java config equivalent would be you creating a @Bean that returns the JndiObjectFactoryBean and another having another bean for UserCredentialsConnetionFactoryAdapter that depends on a ConnectionFactory.

0
Esteban On

I've just faced a very similar issue while trying to convert from XML config to beans and I've found the right answer was in the comments (thanks!), but it wasn't clear enough.

To handle the mismatch, you need to get the object from JndiObjectFactoryBean and cast it to the appropiate type.

connectionFactory.setTargetConnectionFactory((ConnectionFactory)targetConnectionFactory.getObject());