Announcement Announcement Module
Collapse
No announcement yet.
Inject java.util.Calendar instance Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Inject java.util.Calendar instance

    How may I inject a java.util.Calendar instance into a bean? Also, how can I set the instance's time?

    My naivety says I can create a java.util.Calendar instance using the following:

    init-method="getInstance" abstract="true" scope="singleton"

    But, that doesn't work.

    Suggestions? Thanks.

  • #2
    This might be useful.
    http://static.springframework.org/sp...ans-conversion

    Comment


    • #3
      Sample code

      Hi oaktree,

      The following should work:

      Code:
      <beans>
      
         <bean id="calendar" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
            <property name="staticMethod"><value>java.util.Calendar.getInstance</value></property>
         </bean>
      
      </beans>
      By default, the "singleton" property of the MethodInvokingFactoryBean is "true".

      -Arthur Loder

      Comment


      • #4
        Originally posted by oaktree View Post
        How may I inject a java.util.Calendar instance into a bean? Also, how can I set the instance's time?

        My naivety says I can create a java.util.Calendar instance using the following:

        init-method="getInstance" abstract="true" scope="singleton"

        But, that doesn't work.
        abstract="true" prevents the bean declaration from creating the actual bean. You need a concrete bean declaration to get instances.

        The @init-method is the wrong one. What you need is @factory-method.

        Jörg
        Last edited by Jörg Heinicke; Nov 1st, 2006, 03:08 PM.

        Comment


        • #5
          Set the calendar

          Hi oaktree,

          Also, this might work for setting the date explicitly (using the Calendar.set(int, int, int) method):

          Code:
          <beans>
          
             <bean id="currentCalendar" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
                <property name="staticMethod"><value>java.util.Calendar.getInstance</value></property>
             </bean>
          
             <bean id="januaryFirst2006" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
                <property name="targetObject"><ref local="currentCalendar"/></property>
                <property name="targetMethod"><value>set</value></property>
                <property name="arguments">
                   <list>
                      <value>2006</value>
                      <value>0</value>
                      <value>1</value>
                   </list>
                </property>
             </bean>
          
          </beans>
          I can't test this, so this may not work...

          -Arthur Loder

          Comment


          • #6
            Hi Oaktree,

            I think the problem with my previous post is that the Calendar.set method does not return the Calendar object, so the configured Calendar is not returned from the FactoryBean.

            Creating a specific FactoryBean implementation might be a good way to go:

            CalendarFactoryBean.java:
            Code:
            package org.spring.forum;
            
            import java.util.Calendar;
            
            import org.springframework.beans.factory.config.AbstractFactoryBean;
            
            public class CalendarFactoryBean extends AbstractFactoryBean  {
            
            	/**
            	 * Year; defaults to zero.
            	 */
            	private int year = 0;
            
            	/**
            	 * Month; defaults to zero.
            	 */
            	private int month = 0;
            
            	/**
            	 * Date; defaults to zero.
            	 */
            	private int date = 0;
            
            	/**
            	 * Number of hour of day (24 hour); defaults to zero.
            	 */
            	private int hourOfDay = 0;
            
            	/**
            	 * Number of minutes; defaults to zero.
            	 */
            	private int minute = 0;
            
            	/**
            	 * Number of seconds; defaults to zero.
            	 */
            	private int second = 0;
            
            	public void setYear(int year) {
            		this.year = year;
            	}
            
            	public void setMonth(int month) {
            		this.month = month;
            	}
            
            	public void setDate(int date) {
            		this.date = date;
            	}
            
            	public void setHourOfDay(int hourOfDay) {
            		this.hourOfDay = hourOfDay;
            	}
            
            	public void setMinute(int minute) {
            		this.minute = minute;
            	}
            
            	public void setSecond(int second) {
            		this.second = second;
            	}
            
            	@Override
            	protected Object createInstance() throws Exception {
            		Calendar calendar = Calendar.getInstance();
            		calendar.set(this.year, this.month, this.date, this.hourOfDay, this.minute, this.second);
            		return calendar;
            	}
            
            	public Class getObjectType() {
            		return Calendar.class;
            	}
            
            }
            Sample applicationContext.xml:
            Code:
            <?xml version="1.0" encoding="UTF-8" ?>
            <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
            
            <beans>
            
               <bean id="janFirst2006" class="org.spring.forum.CalendarFactoryBean">
                  <property name="year" value="2006" />
                  <property name="month" value="0" />
                  <property name="date" value="1" />
               </bean>
            
               <bean id="janFirst2006_noon" class="org.spring.forum.CalendarFactoryBean">
                  <property name="year" value="2006" />
                  <property name="month" value="0" />
                  <property name="date" value="1" />
                  <property name="hourOfDay" value="12" />
               </bean>
            
            </beans>
            -Arthur Loder

            Comment


            • #7
              Here is another flavor of the same thing. The difference is you can add or set values of a calendar instance in case you needed "today". In my case I needed midnight tomorrow whenever my server starts.

              Code:
              public class CalendarFactoryBean extends AbstractFactoryBean {
                  /**
                   * Year; defaults to zero.
                   */
                  private String year;
                  /**
                   * Month; defaults to zero.
                   */
                  private String month;
                  /**
                   * Date; defaults to zero.
                   */
                  private String dayOfMonth;
                  /**
                   * Number of hour of day (24 hour); defaults to zero.
                   */
                  private String hourOfDay;
                  /**
                   * Number of minutes; defaults to zero.
                   */
                  private String minute;
                  /**
                   * Number of seconds; defaults to zero.
                   */
                  private String second;
                  /**
                   * Number of milliseconds
                   */
                  private String milliSecond;
              
                  public void setYear(String year) {
                      this.year = year;
                  }
              
                  public void setMonth(String month) {
                      this.month = month;
                  }
              
                  public void setDayOfMonth(String dayOfMonth) {
                      this.dayOfMonth = dayOfMonth;
                  }
              
                  public void setHourOfDay(String hourOfDay) {
                      this.hourOfDay = hourOfDay;
                  }
              
                  public void setMinute(String minute) {
                      this.minute = minute;
                  }
              
                  public void setSecond(String second) {
                      this.second = second;
                  }
              
                  public void setMilliSecond(String milliSecond) {
                      this.milliSecond = milliSecond;
                  }    
                  /**
                   * Overrridden
                   * @return
                   * @throws Exception
                   */
                  @Override
                  protected Object createInstance() throws Exception {
                      Calendar calendar = Calendar.getInstance();
                      setValue(calendar, Calendar.YEAR, year);
                      setValue(calendar, Calendar.MONTH, month);
                      setValue(calendar, Calendar.DAY_OF_MONTH, dayOfMonth);
                      setValue(calendar, Calendar.HOUR_OF_DAY, hourOfDay);
                      setValue(calendar, Calendar.MINUTE, minute);
                      setValue(calendar, Calendar.SECOND, second);
                      setValue(calendar, Calendar.MILLISECOND, second);        
                      return calendar.getTimeInMillis();
                  }
              
                  public Class getObjectType() {
                      return Calendar.class;
                  }
                  /**
                   * Helper method to either add or set the value of the date
                   * @param calendar The calendar instance
                   * @param constant The calendar field to add of set the value
                   * @param value The value
                   */
                  private void setValue(final Calendar calendar, final Integer constant, final String value) {
                      if (calendar == null || constant == null) {
                          throw new IllegalArgumentException("The calendar and the constant are required");
                      }
                      if (value != null) {
                          if (value.contains("+") || value.contains("-")) {
                              String amountValue = value.substring(1);
                              Integer amount = Integer.parseInt(amountValue);
                              calendar.add(constant, amount);
                          } else {
                              Integer amount = Integer.parseInt(value);
                              calendar.set(constant, amount);
                          }
                      }
                  }
              }
              My Context:
              Code:
                 <bean id="midnightTomorrow" class="com.example.CalendarFactoryBean">
                    <property name="dayOfMonth" value="+1" />
                    <property name="hourOfDay" value="0" />
                    <property name="minute" value="0" />
                    <property name="millisecond" value="0" />      
                 </bean>

              Comment


              • #8
                Hi all,

                I know that this thread is as old as the hills, but in case somebody else will be searching a way to do this and hits this post, there is also a Spring way of doing this without any customizations:

                Code:
                    <bean id="yourPOJO" class="your.package.ClassName">
                        <property name="calendar" ref="calendar" />
                    </bean>
                
                    <bean id="calendar" class="java.util.Calendar" factory-method="getInstance">
                        <constructor-arg ref="timeZone" />
                        <property name="timeInMillis" value="1352902760453" />
                    </bean>
                
                    <bean id="timeZone" class="java.util.TimeZone" factory-method="getTimeZone">
                        <constructor-arg value="UTC" />
                    </bean>
                HTH, Jukka

                Comment

                Working...
                X