When creating applications with Spring, I prefer to declare beans explicitly using Java Config; it keeps Spring configuration centralized, and keeps my classes free of Spring dependencies. One thing that irks me about this approach is that is can make defining beans a bit cumbersome. Thankfully, Intellij’s Live templates make this a doddle.

Live templates are an advanced form of text expansion, whereby typing an abbreviation and pressing Tab will substitute the abbreviation with the template. Variables defined in the template can be populated dynamically, and you can cycle between the variables by pressing Tab repeatedly.

Lets looks at a simple, but typical, bean definition; creating an instance of Jackson’s ObjectMapper.

@Configuration
public class AppConfig {

  @Bean
  public ObjectMapper objectMapper() {
    return new ObjectMapper();
  }
}

With Java Config, the method name becomes the bean name (unless configured explicitly in the @Bean annotation), and is conventionally the camel-cased class name, but it can be whatever you want. I find that I rarely change it from the default.

Defining a Live Template

Go to the Live template settings: File | Settings | Editor | Live Templates. Add a new live template using the ➕ in the top right of the window

In the abbreviation field, input bean, and add a suitable description, e.g. Create a Spring bean.

Set the template text to

@Bean
public $CLASS_NAME$ $BEAN_NAME$() {
  return new $CLASS_NAME$($END$);
}

Click the Edit variables button. The variable names in the template text above will be available automatically. In the expression column for BEAN_NAME, set the value camelCase(CLASS_NAME). This uses a built-in function to create a camel-cased version of the class name, and assigns it to the corresponding variable.

Finally, a context needs to be defined for which this template will apply; essentially, whereabouts in files Intellij will permit the live template to be expanded. Click the Define link below the Template text input, and choose Java | Declaration.

The complete configuration should look something like this: live template config screenshot

Take It for a Spin

Fire up a Spring project and give it a try!

Other JVM Languagues

The example above works great in Java, but what about other JVM languages, such as Kotlin? All that’s required is to define an additional live template, but with a template based on Kotlin syntax, and changing the context to Kotlin | Top-level:

@Bean
fun $BEAN_NAME$(): $CLASS_NAME$ {
  return $CLASS_NAME$($END$);
}