Spring Annotation configuration

Other than XML, we can also define Spring configuration through annotations in a POJO class, which will not be used as a bean. In the previous section, we took Employee task example; let's now take the Student-Assignment example, a similar one. However, this time, we will not use interfaces; instead, we will directly use classes.

So, here is the Assignment class that takes a lambda as a constructor parameter:

    class Assignment(val task:(String)->Unit) { 
      fun performAssignment(assignmentDtl:String) { 
        task(assignmentDtl) 
      } 
    } 

This class takes a lambda as task, to execute it later, inside the performAssignment() method. Here is the Student class that takes Assignment as a property:

    class Student(val assignment: Assignment) { 
      fun completeAssignment(assignmentDtl:String) { 
        assignment.performAssignment(assignmentDtl) 
      } 
    } 

So, Student would depend on its Assignment and an Assignment would depend on its task definition (Lambda). The following diagram describes the dependency flow for this example:

How to depict this dependency flow in code? It's easy with Annotation Config. Here is the Configuration class that we used:

    @Configuration 
    class Configuration { 
 
      @Bean 
      fun student() = Student(assignment()) 
 
      @Bean 
      fun assignment()  
        = Assignment { assignmentDtl -> println
("Performing Assignment $assignmentDtl") } }

Simple and straightforward, isn't it? The class is annotated with @Configuration, and the function to return the Student and Assignment beans is annotated with @Bean.

Now, how to use this class? Simple, like the previous one, take a look at the main function here:

    fun main(args: Array<String>) { 
      val context = AnnotationConfigApplicationContext   
(Configuration::class.java) val student = context.getBean(Student::class.java) student.completeAssignment("One") student.completeAssignment("Two") student.completeAssignment("Three") context.close() }

Instead of ClassPathXmlApplicationContext, we used AnnotationConfigApplicationContext and passed the Configuration class. The rest of the program is the same.

This is the output of the program:

Cropped output of DI with Annotation Configuration program

So, we learned dependency injection with Spring. It's really easy, isn't it? Actually, the Spring Framework makes everything easy; whatever feature they offer, they make it as easy as calling a method from a POJO class. Spring truly utilizes the power of a POJO.

So, as we got our hands on dependency injection, let's move forward with Aspect-oriented programming.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.190.211