Showing posts with label spring. Show all posts
Showing posts with label spring. Show all posts

Thursday, July 22, 2010

How to autowire things in spring

In order to autowire something the following things must be true (that i know of)
  • - The object you are autowiring needs to be annotated with @Component
  • - The object that will contain the autowired object needs to come from the spring context, meaning:
    • - applicationContext.xml needs to have a bean definition of it
    • - the place where its is newed  needs to be replaced with the call to pull it from the WebApplicationContext

Wednesday, December 16, 2009

JdkDynamicAopProxy ClassCastException

Problem:
I am suddenly getting an error after some spring config was changed:

java.lang.ClassCastException: $Proxy47 cannot be cast to com.mycompany.MyConcreteClass

The code looks like this:
MyConcreteClass myClass = (MyConcreteClass) model.get("myClass");

I should add that MyConcreteClass was autoWired with spring elsewhere, and this setup used to work until something was changed in spring config.

Solution:
This is happening because we are casting to the concrete implementation, what needs to be done is that the object needs to be cast to the interface:
MyInterface myClass = (MyInterface) model.get("myClass");

Also, the relevant spring configuration that causes this issue is:

<tx:annotation-driven manager="springTransactionManager" ></tx:annotation-driven>

In order for the proxy to not proxy the interfaces but concrete classes, you need to add the following attribute to the above directive:
proxy-target-class="true"