Search This Blog

Showing posts with label Spring Framework. Show all posts
Showing posts with label Spring Framework. Show all posts

Monday, September 29, 2014

Spring @Value and javax.inject.Provider for Changeable Property Injection

Introduction


With Spring and other DI containers one works with 'properties' that are used to configure values. Some values might needs to be changed dynamically at runtime while others might be statically configured. A changeable property lends itself to a javax.inject.Provider style where the property is obtained as required and used. Sure that one could inject a java.util.Properties class and use it to obtain the corresponding property. It just seems more in line with The Law of Demeter to inject the actual property or the next closest thing, i.e., a dedicated Provider of the property.

Spring has the support for injecting a property via @Value annotation as :
public class Foo {
 @Value("${fooVal}") 
 private Integer integer;
 ...
}
or Constructor Injection
public class Foo {

 private final Integer integer;
 
 public Foo(@Value("${fooVal}") Integer integer) {
   this.integer = integer;
 }
 ...
}
or Setter Injection
public class Foo {

 private Integer integer;
 
 @Inject
 public setInteger(@Value("${fooVal}") Integer integer) {
   this.integer = integer;
 }
 ...
}

Or if using JavaConfig:
@Configuration
public class FooConfig {
  @Bean
  public Foo foo(@Value("${fooVal}") Integer integer) {
    return new Foo(integer);
  }
}

If fooVal never changes during the execution of the program, great, you inject it and then its set. What if it were to change, due to it being a configurable value? What would be nice to do is the following:
public class Foo {
  private final Provider<Integer> integerProvider;
  
  public Foo(Provider<Integer> integerProvider) {
    this.integerProvider = integerProvider;
  }
  
  public void someOperation() {
    Integer integer = integerProvider.get(); // Current value of fooVal
    ..
  }
}

@Configuration
public class FooConfig {
  @Bean
  public Foo foo(@Value("${fooVal}") Provider<Integer> integerProvider) {
    return new Foo(integer);
  }
}
Looks pretty reasonable, however, when you attempt the same with Spring Java Config, you end up with:
org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.IllegalArgumentException: MethodParameter argument must have its nestingLevel set to 1
 at org.springframework.beans.TypeConverterSupport.doConvert(TypeConverterSupport.java:77)
 at org.springframework.beans.TypeConverterSupport.convertIfNecessary(TypeConverterSupport.java:47)
 at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:875)

This should just work. Simplest way I could get it to work is to fool spring that the nesting level of the Provider<Integer&gt; is actual one level lesser. The way I did it was to create my own org.spring.framework.beans.TypeConverter that delegated to the default TypeConverter used by Spring, i.e., the SimpleTypeConverter:
public class CustomTypeConverter implements TypeConverter {
  private final SimpleTypeConverter simpleTypeConverter;

  public CustomTypeConverter() {
    simpleTypeConverter = new SimpleTypeConverter(); // This is the default used by Spring
  }

  public <T> T convertIfNecessary(Object newValue, Class<T> requiredType,
    MethodParameter methodParam) throws IllegalArgumentException {
    Type type = methodParam.getGenericParameterType();

    MethodParameter parameterTarget = null;

    if (type instanceof ParameterizedType) {
      ParameterizedType paramType = ParameterizedType.class.cast(type);
      Type rawType = paramType.getRawType();

      if (rawType.equals(Provider.class)
          && methodParam.hasParameterAnnotation(Value.class)) { 
        // If the Raw type is javax.inject.Provider, reduce the nesting level
        parameterTarget = new MethodParameter(methodParam); 
       // Send a new Method Parameter down stream, don't want to fiddle with original
        parameterTarget.decreaseNestingLevel();
      }
    }

    return simpleTypeConverter.convertIfNecessary(newValue, requiredType, parameterTarget);
  }
  ...// Delegate other methods to simpleTypeConverter
}
With the above you could do the following:
public class SpringTest {

  @Test
  public void test() {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    context.getBeanFactory().setTypeConverter(new CustomTypeConverter());
    context.register(SimpleConfig.class);
    context.refresh();
    
    context.getBean(SimpleBean.class).print();
  }
  
  public static class SimpleConfig {
    
    @Bean(name = "props") // Change this to a something that detects file system changes and pulls it in
    public PropertyPlaceholderConfigurer propertyPlaceHolderConfigurer() {
      PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
      Resource location = new ClassPathResource("appProperties.properties");
      configurer.setLocation(location);
      return configurer;
    }
    
    @Bean
    public SimpleBean simpleBean(@Value("${fooVal}") Provider<Integer> propValue,
      @Value("${barVal}") Provider<Boolean> booleanVal) {
      return new SimpleBean(propValue, booleanVal);
    }
  }
  
  public static class SimpleBean {
    private final Provider<Integer> propVal;
    private final Provider<Boolean> booleanVal;
    
    public SimpleBean(Provider<Integer>, Provider<Boolean> booleanVal) {
      this.propVal = propValue;
      this.booleanVal = booleanVal;
    }
    
    public void print() {
      System.out.println(propVal.get() + "," + booleanVal.get());
    }
  }
}
Now with the above if your properties changes, as you are injecting a javax.inject.Provider to the SimpleBean, at runtime, it will obtain the current value to use.

All this is great, I understand that I am hacking Spring to get what I want, is this the best way to handle something like dynamically changeable properties? Thoughts and suggestion welcomed.

Update :
I filed an enhancement request with Spring maintainers and they were fast to respond with this actually being a bug and are back porting fixes to previous versions as well as ensuring current and future versions have this feature available. https://jira.spring.io/browse/SPR-12297 

Saturday, January 24, 2009

Spring Jms Support

My year at Overstock.com has been just superb from a learning front. I have had the oppurtunity to work RESTful Web Services, Maven, Hibernate and in general be a part of a super architecture and development team at play.

I have also been able to contribute in the selecting of a JMS provider/architecture for reliable messaging at Overstock. The provider that we have selected is Oracle WebLogic.

As we enter the world of WebLogic JMS, I find that there are items that are best abstracted away such that developers of an application can easily utilize the provider without having to repeat code. Spring's JMS support feels ideal for the same.

Obtaining JMS Artifacts from JNDI:



Properties p = new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
p.put(Context.PROVIDER_URL, "t3://localhost:8000,localhost:8002");
p.put(Context.SECURITY_PRINCIPAL, "weblogic");
p.put(Context.SECURITY_CREDENTIALS, "weblogic");

JndiTemplate template = new JndiTemplate(p);

QueueConnectionFactory connFactory = (QueueConnectionFactory)
template.execute(new JndiCallBack() {
public Object doInContext(Context ctx) {
return (QueueConnectionFactory) ctx.lookup("connectionFactory");
}
});
....




JmsTemplate:
Spring Framework provides a Template class called JmsTemplate much like HibernateTemplate for Hibernate DAO. The class provides many convinience methods for sending recieving messages by providing an abstraction layer over the JMS API. There are methods such as send/receive or methods that accept Call Backs. I like some of the safety these methods provide where Connections, Sessions, Producers and Consumers are gracefully closed after use of them. WebLogic documentation explicitly states that Connection objects must be closed after using them.

That said, I also fear that this class is very open for misuse. James Strachan has mentioned some of the PIT falls that one needs to be aware of when using JmsTemplate. The primary concern that surfaces with the JmsTemplate creating a Connection/Session/Producer or Consumer across every send/receive/callback. This can easily be misused and in the case of WebLogic, attempting to use the template with the default Connection Factory degrades the performance of operations. I fear that directly using the JmsTemplate can lead to code like:



jmsTemplate.send(new MessageCreator() {
public Message send(Session session) throws JMSException {
return session.createTextMessage("Order Submited");
}
});

... do some stuff..
jmsTemplate.send(new MessageCreator() {
public Message send(Session session) throws JMSException {
return session.createTextMessage("Order completed");
}
});



For each of the send operations above, a Connection, Session and Producer will be created. If the above sequence is being called many times over, this would present a performance problem.

With CallBacks like Connection/Session or Producer, re-use has more of chance as within a call back one could send multiple messages thus re-using the jms objects. However, if these operations are many, than these too can suffer misuse and cause performance degradation. JmsTemplate works I guess when you send a message once in a while.

James observation regarding the use of JmsTemplate is very astute and using JmsTemplate might not be best of options unless "Pooling" is introduced into the mix.

Spring Message Container:
Spring offers support for Message Driven POJOs (MDP) in the form of MessageListenerContainers. The Container is responsible for retrieving a message from a JMS destination and then notifying the listener associated with the Container. One nice feature of the Container is that it provides for re-connect logic in event of failure of a server in a Cluster by allowing transparent reconnect to different server in the cluster. Look at this POSTING about a Reconnecting Message Listener. The Spring Message ListenerContainer's tend to Pool Jms artifacts as well. In particular the DefaultMessageListenerContainer provides XA support as well. Using a Container to receive messages is as simple as:




SimpleMessageContainer container = new SimpleMessageContainer();
container.setConnectionFactory(connectionFactory);
container.setDestination(queue);
// Set how many concurrent consumers
container.setConcurrentConsumers(10);
consumer.setMessageListener(new javax.jms.MessageListener() {
public void onMessage(Message m) {
..do some stuff...
}
});
container.start();




Message Converters:
I feel that the SimpleMessageConverter class has some nice convinience methods for converting from POJO's to JMS Messages and vice versa. Message Converters are IMO a great concept for message translation. No whining here.

All in all, I think using Spring's MessageContainer is advisable considering it has all the logic for reconnect, multi-threading, XA etc all build in. Using the Converters has benefit and the JndiTemplate serves to abstract away boiler plate code. However, using Jms Template needs to be done with great care with Pooling almost a must. Jenks might be an option.