Chapter 3. Quick start

This chapter provides a basic tutorial for getting started with JavaConfig. For full details on JavaConfig's capabilities, please refer to Part II, “API Reference”

3.1. Download JavaConfig

Like any Java library, you'll first need to get the JavaConfig jar (and the jars it depends on) into your classpath.

3.1.1. Manual download

Please visit http://www.springframework.org/javaconfig where you'll find links to zip file distributions. Three distributions are available:

  1. spring-javaconfig-1.0.0.m3.zip
  2. spring-javaconfig-1.0.0.m3-with-minimal-dependencies.zip
  3. spring-javaconfig-1.0.0.m3-with-dependencies.zip

The -with-minimal-dependencies zip contains only those jars that are required for basic JavaConfig functionality, while the -with-dependencies zip contains all dependencies, including those required for AOP support.

3.1.2. Maven 2

Assuming your project uses a Maven2 build infrastructure, using JavaConfig is as simple as adding the following to your POM

<dependencies>
    <dependency>
        <groupId>org.springframework.javaconfig</groupId>
        <artifactId>spring-javaconfig</artifactId>
        <version>1.0.0.m3</version>
    </dependency>
</dependencies>

[Note]Note
Please note that this release is not published at the central Maven repository. Instead it is published on Amazon's S3 service, like all Spring milestones. To use it, add the following repository to your POM:
<repository>
    <id>spring-milestone</id>
    <name>Spring Milestone Repository</name>
    <url>http://s3.amazonaws.com/maven.springframework.org/milestone</url>
</repository>

[Tip]Tip
See Appendix C, Maven2 POM configurations for more information about using Maven2 with Spring JavaConfig

3.2. Create bean definitions

@Configuration
public class ApplicationConfig {
    @Bean
    public TransferService transferService() {
        return new TransferServiceImpl(accountRepository());
    }

    @Bean
    public AccountRepository accountRepository() {
        return new JdbcAccountRepository(dataSource());
    }

    @Bean
    public DataSource dataSource() {
        return new DriverManagerDataSource(...);
    }
}

3.3. Retrieve bean instances

Let's create a very basic, command-line application to allow users to transfer money from one account to another.

public class SimpleTransferApplication {
    public static void main(String... args) {
        double amount = new Double(args[0]);
        int sourceAcctId = new Integer(args[1]);
        int destAcctId = new Integer(args[2]);

        JavaConfigApplicationContext context = new JavaConfigApplicationContext(ApplicationConfig.class);
        TransferService transferService = context.getBean(TransferService.class);
        transferService.transfer(300.00, sourceAcctId, destAccountId);
    }
}

3.4. Summary

That's it! You're now ready for Part II, “API Reference”, where you'll walk through each of the features of Spring JavaConfig.