user1143609
user1143609

Reputation: 41

Caused by: java.lang.ClassCastException: $ProxyX cannot be cast to my.package.DefaultCustomerProviderImpl

In my java class I have:

@Autowired
@Qualifier("customerProviderExec")
private DefaultCustomerProvider customerProvider;

And in my context configuration XML

<bean id="customerProviderExec" class="my.package.DefaultCustomerProviderExecutor">
    <property name="defaultCustomerProviderService" ref="customerProviderImpl" />   
</bean> 

<bean id="testCustomerProviderImpl" class="my.package.DefaultCustomerProviderTest">
    <property name="customerProviderImpl" ref="customerProviderImpl" />
</bean>    

<bean id="customerProviderImpl" class="my.package.DefaultCustomerProviderImpl">
    ...
</bean>

Important: The class DefaultCustomerProviderImpl implements DefaultCustomerProvider

When I try to execute in my Java class:

DefaultCustomerProviderExecutor executor = (DefaultCustomerProviderExecutor)this.getCustomerProvider();
return (DefaultCustomerProviderImpl) executor.getDefaultCustomerProviderService();      

I get the error:

Caused by: java.lang.ClassCastException: $Proxy17 cannot be cast to my.package.DefaultCustomerProviderImpl

Has someone been throug this?

Upvotes: 1

Views: 7888

Answers (2)

Marco Mondini
Marco Mondini

Reputation: 142

return (DefaultCustomerProvider) executor.getDefaultCustomerProviderService();

Casting to the implementation is defying the meaning of having an interface defined.

Upvotes: 1

Cjxcz Odjcayrwl
Cjxcz Odjcayrwl

Reputation: 22847

Why do you cast interface to its implementation? Interfaces are to prevent this. You should normally use only interface.

Since by default Spring does not generate proxy for classes, only Java proxies, the bean you get from context is implementing all the bean's interface, but does not extend the bean itself (original bean is only wrapped by the proxy).

Upvotes: 0

Related Questions