1

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?

skaffman
  • 398,947
  • 96
  • 818
  • 769
user1143609
  • 41
  • 1
  • 3
  • 2
    You probably use AOP to perform some cross-cutting concern. Check the accepted answer here: http://stackoverflow.com/questions/3852564/abstract-dao-pattern-and-springs-proxy-cannot-be-cast-to-problem – Kurt Du Bois Feb 01 '12 at 14:15

2 Answers2

1
return (DefaultCustomerProvider) executor.getDefaultCustomerProviderService();

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

0

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).

Danubian Sailor
  • 1
  • 38
  • 145
  • 223