Appendix B. Spring Java Configuration Tips

B.1. Spring Java Configuration Tips

Note that auto-completion in Eclipse and STS is CTRL+Space, even on a Mac.

B.2. Barebones Bean Definitions

Consider writing @Configuration classes where each bean method is defined as a skeleton, just returning null. If you do this first:

  • It allows you to think first about what beans you need, and only later about how to create each one
  • When you come to do dependency injection, auto-completion can be used to select the bean method to invoke as you write the body of each method
@Configuration
public class AppConfig {

    @Bean
    public AccountService accountService() {
        return null;
    }

    @Bean
    public AccountRepository accountRepository() {
        return null;
    }

    @Bean
    public CustomerRepository customerRepository() {
        return null;
    }
}

B.3. Dependency Injection

Dependency injection should be performed one of three ways.

  1. Local dependency, invoke the bean method:

    @Bean
    public AccountService accountService() {
        return new AccountService(accountRepository(), customerRepository());
    }
    
  2. External dependency, defined in a different @Configuration class. Option 1: Use @Autowired:

    @Configuration
    public class AppConfig {
    
        private DataSource dataSource;
    
        @Autowired
        public AppConfig(DataSource dataSource) {
            this.dataSource = dataSource;
        }
    
        @Bean
        public CustomerRepository customerRepository() {
            return new CustomerRepository(dataSource);
        }
    }
    
  3. External dependency, defined in a different @Configuration class. Option 2: Use a method parameter:

    @Configuration
    public class AppConfig {
    
        @Bean
        public CustomerRepository customerRepository(DataSource dataSource) {
            return new CustomerRepository(dataSource);
        }
    }