Sunday, June 17, 2012

Why @Required not working?

In order for @Required to function properly, even though I have the code below in place, but it still doesn't guarantee the code is working fine.

public class MyClass {
   private MyObject theObject;
   @Required
   public void setObject(MyObject theObject) {
      this.theObject = theObject;
   }
}

I have to put in extra code in the Spring configuration file in order to get it work.

In Spring configuration, the header must have this:

< beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd" />

After the header, put in this:

   < context:annotation-config />

Assuming code below exists in the Spring configuration file.

   < bean id="myClass" class="org.huahsin68.MyClass" >
      < !-- < property name="theObject" >
         < ref bean="theObject" /> -- >
      < /property >
   < /bean>

When the code is run, immediately the compiler will response this:

Caused by: org.springframework.beans.factory.BeanInitializationException: Property 'theObject' is required for bean 'sequenceGenerator'

No comments: