36 articles and counting
      

Spring – Developing with Annotations

Annotation-Based Dependency Injection

  • you can use annotations to the point where you hardly need specify any XML configuration at all
  • the following annotations can be used to mark fields, methods and constructors:@Autowired – directs Spring to autowire fields, methods or constructors by using the type
    (Autowiring means to look for objects defined in Spring with the same name as your object property)

    @Resource(”beanName”) – directs Spring to inject the identified bean by its name. This is useful where 2 beans have the same type and autowiring does not work. It works for all methods (not just setters)

    @PostConstruct / @PreDestroy – these perform the same as:
    init-method / destroy-method (configuration attributes) and
    InitializingBean / DisposableBean (interfaces for legacy post-processing bean support prior to Spring 2.5)

    NOTE: all the above annotations must be ‘turned on’ in Spring ie. example using context namespace <context:annotation-config/>

  • the following annotations work at the class level: @Component – identifies a POJO as a Spring bean. This removes the need to specify almost anything in XML. It can optionally provide a string for the bean name*, or else by default the bean name is the non-capitalized/non-qualified name of the class.

    *Its bad practise to put the bean name in with your jave code though.

    NOTE: we need to turn component scanning on for this annotation to work ie. using context namespace <context:component-scan base-package=”transfer”/>

    @Scope – allows you to scope the object eg. @Scope(”Prototype”)

When to Use What (Annotations or XML)?

  • annotations streamline your XML but then you lose the ‘blueprint’ of your application that configuration files can provide in a way
  • Spring IDE may not have full support for some compoents eg. @Autowired, @Component
  • the following could be used as some general guidelines:use annotations:
    - for small isolated parts of the application eg. Spring MVC controllers
    - where annotations are being used across your application already
    - for frequently changing beans
    - @Component may be useful where you have alot of domain objects and do not necessarily always know when they are created

    use XML:
    - where XML is centralized in one (or just a few) places
    - for infrastructure and more ’static’ (unchanging?) beans