Spring Usage

Using ShapeShift with a Spring Boot project.

In this guide we will see how we can use ShapeShift's Spring Boot starter to seamlessly add transformers and decorators within Spring projects.

The Spring Boot starter automatically registers mapping transformer beans and decorator beans, as well as a customizer for cases where further customization of the ShapeShift instance is required.

Installation

Install the spring library via Maven or Gradle:

Maven

<dependency>
  <groupId>dev.krud</groupId>
  <artifactId>spring-boot-starter-shapeshift</artifactId>
  <version>0.8.0</version>
</dependency>

Gradle

Groovy DSL

implementation 'dev.krud:spring-boot-starter-shapeshift:0.8.0'

Kotlin DSL

implementation("dev.krud:spring-boot-starter-shapeshift:0.8.0")

Registering Transformers

In order to register a new transformer, simply create the class and register it as a Spring Bean via your method of choice. (JavaConfig, XML)

Annotation Example

@Component
class BeanTransformer : MappingTransformer<String, String> {
    override fun transform(context: MappingTransformerContext<out String>): String? {
        return context.originalValue?.uppercase()
    }
}

JavaConfig Example

@Configuration
class MyConfiguration {
    @Bean
    fun beanTransformer(): BeanTransformer {
        return BeanTransformer()
    }
}

Default transformers cannot be registered in this way, see Using Customizers below on how to achieve this

Registering Decorators

You can register decorators in the same way that you register transformers, simply create the class and register it as a Spring Bean via your method of choice. (JavaConfig, XML)

Annotation Example

@Component
class BeanDecorator: MappingDecorator<MyPojo, MyPojoDisplay> {
    override fun decorate(context: MappingDecoratorContext<MyPojo, MyPojoDisplay>) {
        // decorate
    }
}

JavaConfig Example

@Configuration
class MyConfiguration {
    @Bean
    fun beanDecorator(): BeanDecorator {
        return BeanDecorator()
    }
}

Using Customizers

If you need to be able to affect the ShapeShift instance in ways that are not mentioned above, you can implement a ShapeShiftBuilderCustomizer, customizers are configuration classes that give you access to the ShapeShiftBuilder for the main Spring instance of ShapeShift. To use, simply implement the interface and annotate with @Configuration. In customize, you can do anything you're normally able to do with the standard ShapeShiftBuilder

@Configuration
class MyCustomizer : ShapeShiftBuilderCustomizer {
    override fun customize(builder: ShapeShiftBuilder) {
        builder.withDefaultMappingStrategy(MappingStrategy.MAP_ALL)
    }
}

Last updated