Java-based configuration
In the previous section, we saw how to configure a bean using XML-based configuration. In this section, we will see the Java-based configuration. The same as XML, Java-based configuration also injects dependency explicitly. The following example defines the Spring bean and its dependencies:
@Configuration
public class AppConfig {
@Bean
public CustomerService showCustomerAccountBalance() {
return new CustomerService();
}
@Bean
public BankingService getBankingService() {
return new BankingService();
}
}
In the Java-based configuration, we must annotate the class with @Configuration, and the declaration of the bean can be achieved with the @Bean annotation. The previous example of a Java-based configuration is equivalent to an XML-based configuration, as per the following code:
<beans>
<bean id="customerService" class="com.packt.springhighperformance.ch2.bankingapp.service.Impl.CustomerServiceImpl" />
<bean id="bankingService"
class="com.packt.springhighperformance.ch2.bankingapp.model.BankingService/">
</beans>
The previous AppConfig class is annotated with the @Configuration annotation, which describes that it is a configuration class of the application that contains the details on bean definitions. The method is annotated with the @Bean annotation to describe that it is responsible for instantiating, configuring, and initializing a new bean is to be managed by the Spring IoC container. In the Spring container, each bean has a unique ID. Whichever method is annotated with @Bean then, by default, that method name will be the bean ID; however, you can also override that default behavior using the name attribute of the @Bean annotation, as follows:
@Bean(name="myBean")
public CustomerService showCustomerAccountBalance() {
return new CustomerService();
}
The Spring application context will load the AppConfig file and create beans for the application.
The following is the MainApp.java file:
public class MainApp {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext(AppConfig.class);
BankingService bankingService =
context.getBean(BankingService.class);
bankingService.showCustomerAccountBalance();
context.close();
}
}