Friday 14 June 2013

Spring annotation problem and fixes

Spring annotation problems and fixes

Multiple bean instances ( duplicate instances )

I have been dealing with spring and glassfish for almost 3 years. I have encountered many problems with bean xml declarations. Latest spring release supports annotations in java level and eliminated the need of xml declarations. But for some declarations like jpa repository, you still need the xml declarations. I feel that this blog will really help for people those who are struggling with duplicate bean instantiation problem because of improper tag definitions.

Spring offers <context:component-scan> tag to scan your source files and instantiate beans. 
We usually place this tag in your applicationContext.xml file.

    <context:component-scan base-package="com.xxxxxx" />

If you are using spring controller, placing this tag in applicationContext.xml is not just enough.
You have to put the same tag in your dispatcher-servlet.xml file to instantiate your spring controllers and map RequestMap annotations.

    <context:component-scan base-package="com.xxxxxx" /> 

Now, you have same tag definitions in applicationContext.xml and dispatcher-servlet.xml.
When spring scans these two files, it will instantiate the beans twice.

To avoid this problem. Use the below tag in applicationContext.xml

    <context:component-scan base-package="com.xxxxxx" >
        <context:exclude-filter expression="org.springframework.stereotype.Controller"
                                type="annotation"/>
    </context:component-scan>


In dispatcher-servlet.xml

   <context:component-scan base-package="com.xxxx" use-default-filters="false">
        <context:include-filter expression="org.springframework.stereotype.Controller" 
                                type="annotation"/>
    </context:component-scan>

  

No comments:

Post a Comment