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”
Like any Java library, you'll first need to get the JavaConfig jar (and the jars it depends on) into your classpath.
Please visit http://www.springframework.org/javaconfig where you'll find links to zip file distributions. Three distributions are available:
spring-javaconfig-1.0.0.m3.zip
spring-javaconfig-1.0.0.m3-with-minimal-dependencies.zip
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.
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 | |
---|---|
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 | |
---|---|
See Appendix C, Maven2 POM configurations for more information about using Maven2 with Spring JavaConfig |
@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(...); } }
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); } }
That's it! You're now ready for Part II, “API Reference”, where you'll walk through each of the features of Spring JavaConfig.