0

what is the best approach for using velocity component inside spring container.

In my velocity util(emailer) class , i have declared the method for sending email as STATIC to avoid creation of emailer object everytime. Also i have declared the setter injections as static.

Is this the correct way ?

Java:

     Class emailer{


    public static Boolean sendEmail(){
     SimpleMailMessage msg = new SimpleMailMessage();  
     String val = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, template, model);
    msg.setText(val);
    mailSender.send(msg);


    }



    private static MailSender mailSender;

@Autowired
public static void setMailSender(MailSender mailsender) {
    LOGGER.debug("MailSender set successfully");
    mailSender = mailsender;
}

private static VelocityEngine velocityEngine;

@Autowired
public static void setVelocityEngine(VelocityEngine velocityengine) {
    LOGGER.debug("Velocity Engine set successfully");
    velocityEngine = velocityengine;
}
    }

xml changes: localhost

<bean id="emailHelper" class="emailer">
  <property name="mailSender" ref="mailSender"/>
  <property name="velocityEngine" ref="velocityEngine"/>

<bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
 <property name="velocityProperties">
 <props>
  <prop key="resource.loader">class</prop>
  <prop key="class.resource.loader.class">
            org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
  </prop>


  </props>
   </property>
   </bean>
Sekhar
  • 961
  • 5
  • 15
  • 27

1 Answers1

0

You shouldn't use static methods here. Spring can't autowire static methods (see Can you use @Autowired with static fields?)

But even if you could autowire static methods, it wouldn't be any better than using instance methods. That's because Spring creates beans as singletons by default, which means it creates only one instance and it uses the same one for each @Autowired property. So it would not create a new instance of your emailer object or your mailsender object every time, it would keep using the same one.

The Spring documentation explains it in more detail.

You should only use instance properties and variables to make it work — in other words, just remove the word static from each one.

Community
  • 1
  • 1
gutch
  • 6,959
  • 3
  • 36
  • 53
  • Yes i agree, but VelocityEngineUtils.mergeTemplateIntoString method is a static one . How will i use it then in my sendEmail() method ? – Sekhar Feb 16 '12 at 07:06
  • You can always call a static method from an instance method — there's nothing wrong with that! – gutch Feb 21 '12 at 22:11