6.2. JavaConfig and Annotation-Driven Configuration

6.2.1. @AnnotationDrivenConfig

Spring 2.5 introduced a new style of dependency injection with Annotation-Driven Injection. In Spring XML, Annotation-Driven Injection is enabled in the container by declaring

<context:annotation-config/>
                

In JavaConfig, this same functionality is enabled with the @AnnotationDrivenConfig annotation

@Configuration
@AnnotationDrivenConfig
public class Config {
    // may now use @Autowired to reference beans from other @Configuration classes, XML, etc
}
                

6.2.2. @ComponentScan

An equivalent for Spring XML's <context:component-scan/> is provided with the @ComponentScan annotation.

package com.company.foo;

@Service
public class FooServiceImpl implements FooService {
    private final FooRepository fooRepository;

    @Autowired
    public FooService(FooRepository fooRepository) {
        this.fooRepository = fooRepository;
    }

    // ...
}
                

package com.company.foo;

@Repository
public class JdbcFooRepository implements FooRepository {
    private final DataSource dataSource;

    @Autowired
    public FooRepository(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    // ...
}
                

@Configuration
@ComponentScan("com.company") // search the com.company package for @Component classes
@ImportXml("classpath:com/company/data-access-config.xml") // XML with DataSource bean
public class Config {
}
                

Because Spring's @Service and @Repository stereotype annotations are each meta-annotated with @Component, they are candidates for component scanning. Because FooServiceImpl and JdbcFooRepository both reside underneath the com.company package, they will be discovered during component scanning and will be autowired together. @ImportXml pulls in the DataSource bean, ensuring it will be available for autowiring into JdbcFooRepository.

With the above very minimal configuration in the Config class, we can bootstrap and use the application as follows:

public class Main {
    public static void main(String[] args) {
        JavaConfigApplicationContext ctx = new JavaConfigApplicationContext(Config.class);
        FooService fooService = ctx.getBean(FooService.class);
        fooService.doStuff();
    }
}
                

Please see "Chapter 3, IoC" of the core spring documentation for additional detail on Annotation-Driven Injection support.