Google

Oct 18, 2013

Spring Java based configuration using @Configuration and @Bean


Traditionally, Spring allows the developer to manage bean dependencies using XML based configuration through the use of application context XML file. This file is external to the application and it holds definition of beans and its dependencies for that application. There is an alternative way to define bean and its dependencies. Its called as Java based configuration.Unlike XML, Java based configuration enables you to manage beans programatically. This can be acheived through use of various annotations.
This is acheived using @Configuration and @Bean annotations as demonstrated in real life example as shown in posts
In this post, let's look at a typical Java configuration based dependency management.


package com.myapp.bdd.stories;

import com.myapp.*;

import org.powermock.api.mockito.PowerMockito;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.Import;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;


@Configuration
//packages and components to scan and includ
@ComponentScan(
        basePackages =
        {
            "com.myapp.calculation.bdd",
            "com.myapp.refdata",
            "com.myapp.dm.dao"
        
        },
        useDefaultFilters = false,
  //interfaces
        includeFilters =
        {           
            @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = MyApp.class),
            @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = MyAppDroolsHelper.class),
            @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = TransactionService.class),
            @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = TransactionValidator.class),
          
            @ComponentScan.Filter(type = FilterType.ANNOTATION, value = org.springframework.stereotype.Repository.class)
        })
//import other config classes  
@Import(
{
    StepsConfig.class,
    DataSourceConfig.class,
    JmsConfig.class,
    PropertiesConfig.class
})
public class StoryConfig
{
    
 
 //creates a partially mocked transaction service class
 
    @Bean(name = "txnService")
    public TransactionService getTransactionService()
    {
        return PowerMockito.spy(new TransactionService());
    }
    
}

As shown the components can be scanned by assignable type or annotation.

Here is another example. Pay attention to the annotations used.

 
package com.myapp.config;

import com.myapp.deadlock.DeadlockRetryAspect;

@Component
@Import(
{
    JmsConfig.class, 
    ExceptionConfig.class
})
@EnableJpaRepositories(basePackageClasses =
{
    Report.class, 
 Transaction.class
})
@ComponentScan(basePackageClasses =
{
    Classifier.class,
    AccountServiceImpl.class,
    TaxDaoImpl.class,
}, useDefaultFilters = false, includeFilters =
{
   
    @Filter(type = FilterType.ASSIGNABLE_TYPE, value = TaxService.class),
    @Filter(type = FilterType.ASSIGNABLE_TYPE, value = Classifier.class),
    @Filter(type = FilterType.ASSIGNABLE_TYPE, value = TaxDao.class),
  
    
    //All the repositories
    @Filter(type = FilterType.ANNOTATION, value = Repository.class),
    
 
})
@Configuration
@PropertySource(
{
    "classpath:reporting/report.properties", 
    "classpath:tax/tax.properties",
    "classpath:exception/exception.properties"
})
public class AccountingConfig
{
}



You can bootsrap the above class as shown below

    
public static void main(String[] args) {
  ApplicationContext ctx = new AnnotationConfigApplicationContext();
  ctx.register(StoryConfig.class)
}




    
public static void main(String[] args) {
  ApplicationContext ctx = new AnnotationConfigApplicationContext();
  ctx.register(AccountingConfig.class)
}



There are plenty of things you can do with Java configuration. The advantage is its type safety and downside is ofcourse you have to re-compile the application if you make any changes to the configuration in your Java class. So, it is worth knowing both Java and XML way of configuring your spring beans. So, don't be baffled if both approiaches are used in the next project you work on. There are more practical examples here.

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home