Sunday, 1 November 2015

Spring dependency injection using annotation based Autowiring

Background



In last post you would have seen what dependency injection is and how is it generally achieved in Spring. It is done using beans that you define in you xml file using tags bean , constructor-arg and property.

But as your project size grows it becomes difficult to keep adding bean in your XML files with its dependencies as the size of xml file continues to grow. So Spring has provided a feature called autowiring where bean dependencies are automatically injected based on various criteria like name, type etc (you can find all types in the previous post). Going a step forward Spring also provides annotations based injection in which case you don't event have to define beans. Spring will scan annotations and inject dependencies on it's own Ofcourse there are rules by which this is governed. We will see this autowiring feature in this post with and without annotations.

Lets continue with the Cricket example we saw in Last post.

Models

Lets rewrite our model classes - 

Bat.java

package models;



public class Bat {    

    private String name;

    public Bat() {}

    

    public Bat(String name) {
        this.name= name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    
    public void play() {
        System.out.println("Bat is swung");
    }

}


Ball.java

package models;

public class Ball {
    

    private String name;


    public Ball() {} 
    

    public Ball(String name) {
        this.name= name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    

    public void play() {
        System.out.println("Ball is bowled");
    }

}

And finally Cricket.java

package models;



public class Cricket {

    private Bat bat;
    private Ball ball;

    public Bat getBat() {
        return bat;
    }

    public void setBat(Bat bat) {
        this.bat = bat;
    }

    public Ball getBall() {
        return ball;]
    }

    public void setBall(Ball ball) {
        this.ball = ball;
    }

    

    public void play() {
        ball.play();
        bat.play();
    }

    

}

now lets configure Spring for these models. 

Spring configuration

Under src folder create a file called beans.xml and add following beans to it

beans.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    

   <bean id="bat" class="models.Bat" />
   <bean id="ball" class="models.Ball" /> 
   <bean id="cricket" class="models.Cricket" autowire="byType"/>

</beans>

Note :  Notice the attribute autowire of tag bean which is set to byType. This means Cricket has dependency on Bat instance so find a bean of type Bat and inject into cricket. You can also set it as byName in which case it will match bean name and inject dependency, However be careful in using this - if spring finds two beans of type Bat it will throw exception.

Now lets run this setup

Main.java

import models.Cricket;



import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {

    
    public static void main(String args[]) {
       
        ApplicationContext context =  new ClassPathXmlApplicationContext("beans.xml");
        Cricket cricket = (Cricket) context.getBean("cricket");
        cricket.play();
    }
    
}
Output :
Ball is bowled
Bat is swung
Now lets see the same thing with annotations.

Note : Note that spring first created beans that are dependencies and then injects in into objects that need them. Also all beans by default are singleton.

Spring dependency injection using annotation based Autowiring

Changes needed
  1. In your beans.xml file remove autowire="byType" from the cricket tag.
  2. In your Cricket class use @Autowired annotation over your Bat and Ball instance variables.
 beans.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:annotation-config/>
    
   <bean id="bat" class="models.Bat" />
   <bean id="ball" class="models.Ball" /> 
   <bean id="cricket" class="models.Cricket" />

</beans>


Cricket.java

public class Cricket {
    
    @Autowired
    private Bat bat;
    @Autowired
    private Ball ball;
    //more code 
} 



Now run the same program as above and you should again get the same output. Few point to note -
  1.  Using @Autowired annotation is same as saying find the bean by type.If Spring finds no bean of injected type for auto-wiring, then it will throw NoSuchBeanDef Exception. If you think that this dependency is not a must than you can use @Autowired(required=false).
  2. As mentioned before @Autowired annotation is similar to autowiting by type. If there are two beans of same type you land in trouble. In such cases you can use resolve by name. For this you can use @Qualifier(value="beanName")
  3. Combination of using @Autowired(required=false) with @Qualifier(value="beanName") is very flexible as you can use this to specify you dependency is not a mandate and you can also specify bean name to resolve with.

To use Qualifier annotation Change your beans.xml as follows

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:annotation-config/>

    
   <bean id="myBat" class="models.Bat" />
   <bean id="myBall" class="models.Ball" /> 
   <bean id="cricket" class="models.Cricket" />

</beans>


and your cricket class as follows

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
public class Cricket {

    
    @Autowired(required=false)
    @Qualifier(value="myBat") 
    private Bat bat

    @Autowired(required=false)
    @Qualifier(value="myBall") 
    private Ball ball;

     //more code 

}


and run the Main class again you should see same result.


Note : If you want to resolve by name then you can use @Resource annotation. Sample usage would be @Resource(name="myBat") . But note here that you loose the flexibility of marking it as non mandatory as you did with @Autowired annotation. All dependencies become mandatory.


Change the Cricket class as

public class Cricket {
    

    @Resource(name="myBat") 
    private Bat bat;

    @Resource(name="myBall") 
    private Ball ball;
   
    //More code
} 



and rerun Main methods. You should see same output.


Related Links

Saturday, 31 October 2015

Spring Dependency Injection

Background



Before we proceed with how dependency injection works in Spring lets see what dependency injection actually is and why is it so important.

Consider a simple example. Lets say we are designing a Cricket game. How will it's class look like?

You will have a Cricket class that will probably have Bat class and Ball class.

public class Cricket {
    private Bat bat;
    private Ball ball;
    
    public Cricket()
   {
        bat = new Bat("MyBat1") ;
        ball= new Ball("MyBall1") ;
   }


   public void play()
   {
         bat.play();
         ball.play(); 
   }
     
}


How would you play cricket? Probably something like

public class Main {
    
    public static void main(String args[]) {
        Cricket cricket1 = new Cricket();

         cricket1.play();       
    }
    
}


What do you think about above code -
  • It is tightly coupled. If you device to change your Bat or Ball you have to write a new Cricket instance. 
  • It will also be very difficult to test. There can be any type of Bat or Ball and each test your need new Cricket instance.

This is where dependency injection comes into picture. Now consider your cricket class as follows.

public class Cricket {
    private Bat bat;
    private Ball ball;
    
    public Cricket(Bat bat, Ball ball) {
        this.bat = bat;
        this.ball = ball;
    }
    
    public void play() {
        bat.play();
        ball.play();
    }
    
}

and you play like

    public static void main(String args[]) {
       
        Bat bat1 =  new Bat("MyBat");
        Ball ball1 =  new Ball("MyBall");
        Cricket cricket1 = new Cricket(bat1, ball1);
        cricket1.play();
       
        Bat bat2 =  new Bat("MyNewBat");
        Ball ball2 =  new Ball("MyNewBall");
        Cricket cricket2 = new Cricket(bat2, ball2);
        cricket2.play();

    }

If you notice you can create and use any type of bat and ball and play cricket with it. All of it is done at runtime. So essentially you are injecting Bat and Ball dependencies into your Cricket object.

Also notice the problems we faced with earlier code are vanished
  • Code is now decoupled. You can use any Bat and Ball to play cricket.
  • Testing has also becomes very easy as you can now mock your Bat and Ball objects and test your cricket.

There are two types of dependency injection
  1. Constructor based dependency injection
  2. Setters based dependency injection
What you saw in code above is constructor based dependency injection. Setter based dependency injection is when you use setters instead of constructor to inject dependency. See following example -


public class Cricket {
    private Bat bat;
    private Ball ball;
    
    public Bat getBat() {
        return bat;
    }

    public void setBat(Bat bat) {
        this.bat = bat;
    }

    public Ball getBall() {
        return ball;
    }

    public void setBall(Ball ball) {
        this.ball = ball;
    }
    
    public void play() {
        bat.play();
        ball.play();
    }
    
}


and you play like

     public static void main(String args[]) {
        
        Bat bat1 =  new Bat("MyBat");
        Ball ball1 =  new Ball("MyBall");
        Cricket cricket1 = new Cricket();
        cricket1.setBat(bat1);
        cricket1.setBall(ball1);
        cricket1.play();
        
        Bat bat2 =  new Bat("MyNewBat");
        Ball ball2 =  new Ball("MyNewBall");
        Cricket cricket2 = new Cricket();
        cricket2.setBat(bat2);
        cricket2.setBall(ball2);
        cricket2.play();

    }


Simply putting

"Dependency injection is basically providing the objects that an object needs (its dependencies) instead of having it construct them itself. It's a very useful technique for testing, since it allows dependencies to be mocked or stubbed out."

That's the dependency injection in general. Now lets come to Spring dependency injection.

Spring Dependency Injection 

In Spring dependency injection Spring container instantiates and injects dependencies in your instance (also called beans) based on the dependency type or name (more on this later) rather that you instantiating and injecting it yourself.


Lets see how spring DI works in case of our above code.

  • Setter DI

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="myBat" class="Bat">
    
    <bean id="myBall" class="Ball">
    
   <bean id="cricket" class="Cricket">
      <property name="bat" ref="myBat"/>
      <property name="ball" ref="myBall"/>
   </bean>

</beans>

Above bean definition uses setter DI. Spring container scans beans and automatically injects dependencies in it. You can also use 
  • Constructor based DI
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="myBat" class="Bat">
    
    <bean id="myBall" class="Ball">
    
   <bean id="cricket" class="Cricket">
      <constructor-arg ref="myBat"/> <!--  constructor argument order should be same-->
      <constructor-arg ref="myBall"/>
   </bean>

</beans>

Notes : 
  1. For values as dependency (like simple String) you can do <property name="brand" ref="MRF"/>
  2. Instead of using property tag you can also use p namespace - <bean id="cricket" class="Cricket" p:brand="MRF" p:bat-ref="myBat" />  (don't forget to add the namespace)
  3. Also note p namespace does not have any schema reference.

Aurowiring

Instead of explicitly providing dependencies to be injected you can autowire them. One simple example is autowiring by type. In this case Spring container will look for bean of dependency type among all beans and inject it. However note if more than one type of such bean exist this will fail.

  • autowire is an attribute in bean tag with following possible values.





Another interesting aspect is spring DI using annotations and component scan. Instead of specifying beans you can directly use annotations and ask spring framework to scan those and autowire. You can see the same in next post -


NOTE : Dependency injection and IoC (Inversion of control) are words used interchangeably. Both mean dependencies are injected rather that created itself by the object which needs the dependencies.

Related Links


Friday, 2 October 2015

Returning value from a thread in python

Background

In this post we will see how python functions can be executed in a new thread and also how can we return some value from it.

NOTE : Python is pass by value similar to java. But for objects it is pass by value of the reference (again just like Java).

Returning value from a thread in python

Create a file called test.py and add the following code to it - 

import threading

print("Starting Test Python Modules");

def threadtarget(array):
    array.append("Hello World!")

array=[]
t = threading.Thread(target=threadtarget, args=(array,))
t.start()
t.join()
print("Value received from thread : " + array[0])
    
print("Terminating Test Python Module");

Explanation :  We are have a simple function threadtarget that accepts a list in it's argument and adds a String called "Hello World!" to it. In our script we are creating a new thread to run the method threadtarget and finally read the value of list we pass to confirm value added by thread to the list is retained.

Execute the script with -
  • python test.py
This is captured in below screenshot



 Related Links

Capturing python output in a file along with the stdout

Background

In last couple of posts we saw how python works and how can we add a shutdown hook in python. Whenever we execute any python script it's output gets logged to the console from which you execute your script. In this post we will see how can we log this output to a file while retaining what gets printed on your console.

Capturing python output in a file along with the stdout

create a file test.py and add following code to it

import atexit
import sys
import datetime
import os

class Logger(object):
    def __init__(self, filename="output.txt"):
        # Initialize the logfile
        self.terminal = sys.stdout
        self.log = open(filename, "a")

        # Write the command and arguments if any
        self.log.write("CMD: " + str(sys.argv) + "\n")
    def __del__(self):
        self.log.flush()
        del self.log
    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)
    def isatty(self):
        return True
    def flush(self):
        self.log.flush()

now = datetime.datetime.utcnow()
if not os.path.exists(os.getcwd() + os.sep + "logs"):
    os.makedirs(os.getcwd() + os.sep + "logs")
logFile = os.getcwd() + os.sep + "logs" + os.sep +'log.txt'
sys.stdout = Logger(logFile)
del now

print("Starting Test Python Modules");

def testmethod():
    print("From test method")

atexit.register(testmethod)    
    
print("Terminating Test Python Module");


Explanation : What above cod does? We are defining a custom class called Logger and defining methods that a stdout object defines. In this new custom class and methods we retain output to console and also add a output to a file whose path can be provided in the objects constructor while instantiating. Finally we say sys.sysout points to this new Logger object. Lets try this out. Run this script
  • python test.py
You should see a directory called logs getting created in current directory and it will have a file called log.txt with your script output. All of this is captured in below screenshot.



Related Links

How Python works?

Background

Since I have covered some of python topics already I thought it would be a nice time to understand how Python actually worked. There is s common misconception that python is a purely interpreted language. We will see how it actually works now.

How Python works?

Python like Java is first compiled into byte codes which is the interpreted by Python VM by running an interpreter.

  1. When a module is imported for the first time, or when the source is more recent than the current compiled file, a .pyc file containing the compiled code will usually be created in the same directory as the .py file. When you run the program next time, Python uses this file to skip the compilation step.
  2. Running a script is not considered an import and no .pyc will be created. For example, if you have a script file abc.py that imports another module xyz.py, when you run abc, xyz.pyc will be created since xyz is imported, but no abc.pyc file will be created since abc.py isn’t being imported.
  3. You can manually compile your source file using compileall module. You can just say python -m compileall -l test.py and that should create your compiled .pyc file under a directory called __pycache__ under your current directory. Thereafter you can directly run this .pyc file using python test.cpython-34.pyc  (All of this is captured below in the screenshot)



As I mentioned before the imported modules are automatically compiled for further use. Lets see how that works out.

In my current folder I have two py files
  1. test.py and
  2. testlib.py
testlib.py has a method called helloworld which simply prints "Hello World!" to the console.

It's contents are as follows

test.py

import testlib

print("Test Python Module")
testlib.helloworld()


testlib.py

def helloworld():
    print("Hello World!")

Now lets run our test.py and see the results. You will see the output and also see a __pycache__ directory getting create under current directory with compile testlib.pyc file. All of this is captured is screenshot below



Note : Only difference is imported modules are compiled to pyc files automatically based on timestamps where as your source files are compiled on the fly. To compile your source files you can use compileall module.

Compiled files with bytecodes are faster to run by python interpreter. Generally .pyc files are the once you ship.

Note :  " It's worth noting that while running a compiled script has a faster startup time (as it doesn't need to be compiled), it doesn't run any faster. "

Given above note will help you understand why modules are compiled and not the main source file. Byte compiled modules simply help in faster startup time.

Related Links

  1. Shutdown hook in Python(OSFG) 
  2. Using Fabric Python command-line tool(OSFG) 
  3. Difference between functions and methods. (OSFG)
  4. If Python is interpreted, what are .pyc files? (SO)
  5. How to avoid .pyc files? (SO)
  6. Difference between Compiler, Interpreter and Assembler (OSFG)
  7. compileall python module documentation
t> UA-39527780-1 back to top