Using spring annotations

In a previous post I implemented a simple bean and created the SpringBeans configuration file, but spring can also be used with annotations (attributes to us .NET people).

So let’s take the previous posts code and amend it to use annotations.

  • Remove or comment out the contents of SpringBeans.xml
  • Change the HelloWorld bean to look like this
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    
    @Component
    public class HelloWorld {
        private String name;
    
        public void setName(String name) {
            this.name = name;
        }
    
        public void output() {
            System.out.println("Bean says " + name);
        }
    }
    
  • Change the main method to look like this
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    
    public static void main( String[] args )
    {
       AnnotationConfigApplicationContext context =
          new AnnotationConfigApplicationContext(IocConfiguration.class);
    
       HelloWorld obj = (HelloWorld) context.getBean("helloBean");
       obj.output();
    }
    
  • We still need a way to define how our beans are going to be created. We’re going to do this via a class, which we’ll name IocConfiguration (the name is unimportant), here’s the class
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    public class IocConfiguration {
    
        @Bean(name = "helloBean")
        public HelloWorld getHelloWorld() {
            HelloWorld o = new HelloWorld();
            o.setName("Hello World");
            return o;
        }
    }
    
  • Now before you can using the @Configuration you’ll need to update the Maven pom.xml to download cglib, so add the following dependency
        <dependency>
          <groupId>cglib</groupId>
          <artifactId>cglib</artifactId>
          <version>2.2.2</version>
        </dependency>
    
  • Run mvn install and now build and run the application.