Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Spring Method Injection with Java Configuration

DZone's Guide to

Spring Method Injection with Java Configuration

· Java Zone ·
Free Resource

The CMS developers love. Open Source, API-first and Enterprise-grade. Try BloomReach CMS for free.

Last week, I described how a Rich Model Object could be used with Spring using Spring’s method injection from an architectural point of view.

What is missing, however, is how to use method injection with my new preferred method for configuration, Java Config. My start point is the following, using both autowiring (<shudder>) and method injection.

public abstract class TopCaller {
 
    @Autowired
    private StuffService stuffService;
 
    public SomeBean newSomeBean() {
 
        return newSomeBeanBuilder().with(stuffService).build();
    }
 
    public abstract SomeBeanBuilder newSomeBeanBuilder();
}

Migrating to Java Config requires the following steps:

  1. Updating the caller structure to allow for constructor injection
  2. For method injection, provide an implementation for the abstract method in the configuration class
  3. That’s all…

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
 
@Configuration
public class JavaConfig {
 
    @Bean
    public TopCaller topCaller() {
 
        return new TopCaller(stuffService()) {
 
            @Override
            public SomeBeanBuilder newSomeBeanBuilder() {
 
                return someBeanBuilder();
            }
        };
    }
 
    @Bean
    public StuffService stuffService() {
 
        return new StuffService();
    }
 
    @Bean
    @Scope(BeanDefinition.SCOPE_PROTOTYPE)
    public SomeBeanBuilder someBeanBuilder() {
 
        return new SomeBeanBuilder();
    }
}

BloomReach CMS: the API-first CMS of the future. Open-source & enterprise-grade. - As a Java developer, you will feel at home using Maven builds and your favorite IDE (e.g. Eclipse or IntelliJ) and continuous integration server (e.g. Jenkins). Manage your Java objects using Spring Framework, write your templates in JSP or Freemarker. Try for free.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}