Archive

Posts Tagged ‘spring framework’
  • Open your classes and methods in Kotlin

    Kotlin icon

    Though Kotlin and Spring Boot play well together, there are some friction areas between the two. IMHO, chief among them is the fact that Kotlin classes and methods are final by default.

    The Kotlin docs cite the following reason:

    The open annotation on a class is the opposite of Java’s final: it allows others to inherit from this class. By default, all classes in Kotlin are final, which corresponds to Effective Java, Item 17: Design and document for inheritance or else prohibit it.

    Kotlin designers took this advice very seriously by making all classes final by default. In order to make a class (respectively a method) inheritable (resp. overridable), it has to be annotated with the open keyword. That’s unfortunate because a lot of existing Java libraries require classes and methods to be non-final. In the Spring framework, those mainly include @Configuration classes and @Bean methods but there also Mockito and countless other frameworks and libs. All have in common to use the cglib library to generate a child class of the referenced class. Ergo: final implies no cglib implies no Spring, Mockito, etc.

    That means one has to remember to annotate every required class/method. This is not only rather tedious, but also quite error-prone. As an example, the following is the message received when one forgets about the annotation on a Spring configuration class:

    org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem:
    @Configuration class 'KotlindemoApplication' may not be final. Remove the final modifier to continue.
    

    Here’ what happens when the @Bean method is not made open:

    org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem:
    @Bean method 'controller' must not be private or final; change the method's modifiers to continue
    

    The good thing is that the rule are quite straightforward: if a class is annotated with @Configuration or a method with @Bean, they should be marked open as well. From Kotlin 1.0.6, there’s a compiler plugin to automate this process, available in Maven (and in Gradle as well) through a compiler plugin’s dependency. Here’s the full configuration snippet:

    {% highlight xml linenos %}

    kotlin-maven-plugin org.jetbrains.kotlin ${kotlin.version} all-open org.jetbrains.kotlin kotlin-maven-allopen ${kotlin.version} compile compile compile test-compile test-compile test-compile

    {% endhighlight %}

    Note on lines 10-11 the list of all annotations for which the open keyword is now not mandatory anymore.

    Even better, there’s an alternative plugin dedicated to Spring projects, that makes listing Spring-specific annotations not necessary. Lines 6-13 above can be replaced with the following for a shorter configuration:

    <configuration>
      <compilerPlugins>
        <plugin>spring</plugin>
      </compilerPlugins>
    </configuration>
    

    Whether using Spring, Mockito or any cglib-based framework/lib, the all-open plugin is a great way to streamline the development with the Kotlin language.

    Categories: Technical Tags: kotlinspring frameworkfinal
  • Another post-processor for Spring Boot

    Spring Boot logo

    Most Spring developers know about the BeanPostProcessor and the BeanFactoryPostProcessor classes. The former enables changes to new bean instances before they can be used, while the latter lets you modify bean definitions - the metadata to create the bean. Commons use-cases include:

    • Bootstrapping processing of @Configuration classes, via ConfigurationClassPostProcessor
    • Resolving ${...} placeholders, through PropertyPlaceholderConfigurer
    • Autowiring of annotated fields, setter methods and arbitrary config methods - AutowiredAnnotationBeanPostProcessor
    • And so on, and so forth…

    Out-of-the-box and custom post-processors are enough to meet most requirements regarding the Spring Framework proper.

    Then comes Spring Boot, with its convention over configuration approach. Among its key features is the ability to read configuration from different sources such as the default application.properties, the default application.yml, another configuration file and/or System properties passed on the command line. What happens behind the scene is that they all are merged into an Environment instance. This object can then be injected into any bean and queried for any value by passing the key.

    As a starter designer, how to define a default configuration value? Obviously, it cannot be set via a Spring @Bean-annotated method. Let’s analyze the Spring Cloud Sleuth starter as an example:

    Spring Cloud Sleuth implements a distributed tracing solution for Spring Cloud, borrowing heavily from Dapper, Zipkin and HTrace. For most users Sleuth should be invisible, and all your interactions with external systems should be instrumented automatically. You can capture data simply in logs, or by sending it to a remote collector service.

    Regarding the configuration, the starter changes the default log format to display additional information (to be specific, span and trace IDs but that’s not relevant to the post). Let’s dig further.

    As for auto-configuration classes, the magic starts in the META-INF/spring.factories file in the Spring Cloud Sleuth starter JAR:

    # Environment Post Processor
    org.springframework.boot.env.EnvironmentPostProcessor=\
    org.springframework.cloud.sleuth.autoconfig.TraceEnvironmentPostProcessor
    

    The definition of the interface looks like the following:

    public interface EnvironmentPostProcessor {
      void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application);
    }
    

    And the implementation like that:

    public class TraceEnvironmentPostProcessor implements EnvironmentPostProcessor {
    
      private static final String PROPERTY_SOURCE_NAME = "defaultProperties";
    
      @Override
      public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("logging.pattern.level",
          "%clr(%5p) %clr([${spring.application.name:},%X{X-B3-TraceId:-},%X{X-B3-SpanId:-},%X{X-Span-Export:-}]){yellow}");
        map.put("spring.aop.proxyTargetClass", "true");
        addOrReplace(environment.getPropertySources(), map);
      }
    
      private void addOrReplace(MutablePropertySources propertySources, Map<String, Object> map) {
        MapPropertySource target = null;
        if (propertySources.contains(PROPERTY_SOURCE_NAME)) {
          PropertySource<?> source = propertySources.get(PROPERTY_SOURCE_NAME);
          if (source instanceof MapPropertySource) {
            target = (MapPropertySource) source;
            for (String key : map.keySet()) {
              if (!target.containsProperty(key)) {
                target.getSource().put(key, map.get(key));
              }
            }
          }
        }
        if (target == null) {
          target = new MapPropertySource(PROPERTY_SOURCE_NAME, map);
        }
        if (!propertySources.contains(PROPERTY_SOURCE_NAME)) {
          propertySources.addLast(target);
        }
      }
    }
    

    As can be seen, the implementation will add both the logging.pattern.level and the spring.aop.proxyTargetClass properties (with relevant values) to the environment (if they don’t exist yet). If they do, they will be added at the bottom of the list.

    With @Conditional, starters can provide default beans in auto-configuration classes, while with EnvironmentPostProcessor, they can provide default property values as well. Using both in conjunction can go a long way toward offering a great convention over configuration Spring Boot experience when designing your own starter.