/ JAVACONFIG, METHOD INJECTION, SPRING

Spring method injection with Java Configuration

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();
    }
}
Nicolas Fränkel

Nicolas Fränkel

Nicolas Fränkel is a Developer Advocate with 15+ years experience consulting for many different customers, in a wide range of contexts (such as telecoms, banking, insurances, large retail and public sector). Usually working on Java/Java EE and Spring technologies, but with focused interests like Rich Internet Applications, Testing, CI/CD and DevOps. Currently working for Hazelcast. Also double as a teacher in universities and higher education schools, a trainer and triples as a book author.

Read More