May 3, 2013

Wiring up Spring framework Dependency Injection with annotations

Q13. How will you go about wire components using Spring annotations?
A13. Here are the high level steps involved in wiring up a web application in Spring using annotations.

web.xml --> myAppServletContext.xml --> myapp-applicationContext.xml --> --> MyAppService.Java -->

Pay attention to how the different artifacts are wired up using both Spring xml files and annotations. The Spring beans can be wired either by name or type. @Autowired by default is a type driven injection. @Autowired is Spring annotation, while @Inject is a JSR-330 annotation. @Inject is equivalent to @Autowired or @Autowired(required=true). @Qualifier spring annotation can be used to further fine-tune auto-wiring. There may be a situation when you create more than one bean of the same type and want to wire only one of them with a property, in such case you can use @Qualifier annotation along with @Autowired to remove the confusion by specifying which exact bean will be wired.

The Step 3: demonstrates "name" driven wiring up using annotations.

Step 1: The web.xml file snippet.


  <!-- Creates the Spring Container shared by all Servlets and Filters -->

  <-- add resolvers here, if required-->

Step 2: The myAppServletContext.xml file snippet.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
 xmlns:xsi="" xmlns:p=""
 xmlns:mvc="" xmlns:cache=""
 xmlns:aop="" xmlns:jee=""
 xmlns:tx="" xmlns:util=""
 xmlns:batch="" xmlns:cm=""

    <!-- import context files as it is not a best practice to define everything in one xml file-->
 <import resource="classpath:/META-INF/spring/myapp-applicationContext.xml" />
 <!-- scan for any Java based wiring up classes with @Configuration & @Bean annotations -->
 <context:component-scan base-package="com.myapp.camel.config" />
 <!-- exposing beans via JMX  not important for this tutorial -->
 <bean id="exporter" class="org.springframework.jmx.export.MBeanExporter"
  <property name="autodetect" value="true"></property>
  <property name="namingStrategy" ref="namingStrategy"></property>
  <property name="assembler" ref="assembler"></property>
 <bean id="attributeSource"
  class="org.springframework.jmx.export.annotation.AnnotationJmxAttributeSource" />
 <bean id="assembler"
  <property name="attributeSource" ref="attributeSource" />
 <bean id="namingStrategy"
  <property name="attributeSource" ref="attributeSource" />


 Step 3: The myapp-applicationContext.xml snippet with config to enable auto-scan with annotations.

As you can see, the controller, service, and DAO layer classes not configured here as they are scanned via annotation (i,e @Component is the parent annotation from which the other annotations like @Service, @Resource, @Repository etc are defined)

The annotations shown above allow you to declare beans that are to be picked up by autoscanning with <context:component-scan/> or @ComponentScan.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
 xmlns:xsi="" xmlns:p=""
 xmlns:aop="" xmlns:jee=""
 xmlns:tx="" xmlns:util=""
 xmlns:batch="" xmlns:task=""

 <mvc:annotation-driven />
 <context:annotation-config />
 <!-- load properties files -->
 <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
   <property name="ignoreUnresolvablePlaceholders" value="true"/> 
      <property name="location" value="classpath:/myapp/"/>
     <property name="placeholderPrefix" value="$myapp{"/>
  <property name="placeholderSuffix" value="}"/>

    <!-- any packages to exclude for component scanning-->
 <context:component-scan base-package="com.myapp">
  <context:exclude-filter type="regex" expression="com.myapp.camel.config.MyAppCamelConfig"/>
 <!-- comment this line locally to bypass security access control in development. But don't check this in commented as security will be turned off -->
 <!-- Spring security-->
 <security:global-method-security secured-annotations="enabled" pre-post-annotations="enabled" jsr250-annotations="enabled"/>

Step 4: The controller class that handles HTTP requests. Annotations are used to wire up dependencies.

public class MyAppController
    private final MDCLoggingHelper MDCLoggingHelper = new MDCLoggingHelper();
    @Resource(name = "myapp_Service")
    private MyAppService myAppService; 
            value = "/portfolio/{portfoliocd}/summaries",
            method = RequestMethod.GET,
            produces = "application/json")
    public PortfolioSummaryVO retrievePortfolioSummary(
            @PathVariable(value = "portfoliocd") String portfolioCode,
            @RequestParam(value = "valuationDate", required = true) @DateTimeFormat(pattern = "yyyyMMdd") Date valuationDate
            HttpServletResponse response) throws Exception

Step 5: The service class that handles business logic in a protocol agnostic manner. Annotations are used to wire up dependencies.

@Service(value = "myapp_Service")
@Transactional(propagation = Propagation.SUPPORTS)
public class CashForecastServiceImpl implements CashForecastService
 @Resource(name = "myapp_Dao")
    private MyAppDao myAppDao;
    private String defaultFeedDelimiter; //read from files
    public PortfolioSummaryVO  retrievePortfolioSummaries(MyAppPortfolioCriteria criteria,
            FeedFileMetaInfo feedFileMeta) {

Step 6: The DAO class that makes database calls via a JDBC template. The configuration of JDBC template is not shown.

@Repository(value = "myapp_Dao")
public class CashForecastDaoImpl implements CashForecastDao
    @Resource(name = "myapp_JdbcTemplate")
    private JdbcTemplate jdbcTemplateSybase;//configure via jdbcContext.xml
  public PortfolioSummaryVO  retrievePortfolioSummaries(MyAppPortfolioCriteria criteria) {

The @Configuration annotation was designed as the replacement for XML configuration files. The @Configuration annotated classes can still able to use annotated(@Autowired, @Inject etc.) fields and properties to request beans (and even other @Configuration annotated beans too) from the container. Here is an example of how Apache Camel is wired up using the @configuration and @bean annotations in Step 2.



Post a Comment

Subscribe to Post Comments [Atom]

<< Home