Showing posts with label Frameworks. Show all posts
Showing posts with label Frameworks. Show all posts

Thursday, December 18, 2008

Constructor Injection: how it works? Impl using Pico


Implementation of Constructor Injection using Pico. How CI works?

Constructor Injection is mainly used by a highly embeddable, lightweight, and full-service IoC Container named PicoContainer. Should you need to refresh your understanding of DI and its types, go through this article - Dependency Injection & its types>>

Let's see how the Constructor Injection phenomenon works. We will take one example scenario and will implement that using PicoContainer. First we'll see the source code and subsequently we'll discuss how the various pieces of the code fit together and how actually do they work.


Example Scenario: Suppose we have a requirement of displaying bank account details which might come from various sources. The requirement is fairy simple and to implement it we can easily think of having two interfaces, one which would take care of the presentation of the account details and the other would capture the details. Say for example we have named these interfaces as 'DisplayAccount' and 'BankAccount'.




interface DisplayAccount{
void displayAccountDetails(BankAccount bankAccount);
}

interface BankAccount{
Map getAccountDetails(long accountNumber);
}



Source Code: How to code Constructor Injection using PicoContainer?

Since the injection is handled by the constructor and hence it should have the declaration of all the objects that it might depend on.




class DisplayAccountImpl implements DisplayAccount{

private BankAccount bankAccount;
...

public DisplayAccountImpl(BankAccount bankAccount){

this.bankAccount = bankAccount;
}

public void displayAccountDetails(){

/*... display the details as required ...*/
Map acDetails = bankAccount.getAccountDetails();
...
}
...
}

class BankAccountImpl implements BankAccount{

private long accountNumber;
private Map acDetails;
...
...

public BankAccountImpl(long accountNumber){

this.accountNumber = accountNumber;
}

public Map getAccountDetails(){

Map acDetails = new HashMap();

/*... get the details maybe from a DB...*/
/*... form a Map object out of the details ...*/
...
...
...

return acDetails;
}
...
}



Having these two classes well in place, we can now use PicoContainer (or any other IoC Container supporting Constructor Injection such as Spring) to implement the Constructor Injection.




class TestConstructorInjectionWithPico{

private MutablePicoContainer getConfiguredContainer() {

/*... Step #1: get a default Container instance ...*/
MutablePicoContainer picoContainer = new DefaultPicoContainer();

/*... Step #2: populate the Container parameters ...*/
/*... we need to make the parameter value(s) available in this scope ...*/
ConstantParameter constantParameter1 = new ConstantParameter(accountNumber);
...

Parameter[] parametersForBankAccountImpl = {constantParameter1, ...};


/*... Step #3: registering the components with the Container ...*/
picoContainer.registerComponentImplementation(BankAccount.class, BankAccountImpl.class, requiredParameters);
pico.registerComponentImplementation(DisplayAccountImpl.class);

/*... Step #4: return the configured Container instance ...*/
return picoContainer;
}

...

public static void main(String[] args){

/*... get an instance of configured Container ...*/
MutablePicoContainer picoContainer = getConfiguredContainer();

/*... get the components having the injected dependencies ...*/
DisplayAccountImpl displayAccountImpl = (DisplayAccountImpl) picoContainer.getComponentInstance(DisplayAccountImpl.class);

/*... use ready-to-be used components: using for display ac details ...*/
displayAccountImpl.displayAccountDetails();
}
}




Let's try to understand how the above code-segments work. The sample class and interface definitions are fairly simple and straightforward. Coming directly to the getConfiguredContainer method where we are creating an instance of the PicoContainer and configuring the instance. PicoContainer is actually an interface having MutablePicoContainer as one of its various sub-interfaces. The MutablePicoContainer interface has many variants of the method registerComponentImplementation. The two variants which we have used have their signatures as:

  • ComponentAdapter registerComponentImplementation(Object componentKey, Class componentImplementation, Parameter[] parameters) throws PicoRegistrationException;
  • ComponentAdapter registerComponentImplementation(Class componentImplementation) throws PicoRegistrationException;
Here the 'componentKey' is the unique Key within the Container used to identify the component and 'componentImplementation' is the component's implementation class which should of course be a concrete class as otherwise the Container won't be able to create an object of it. The third parameter 'parameters' of type Parameter is an array and it serves as the hint about what all parameters the constructor of the implementing class would require. Depending upon the implementation of the Container, one or more of these hints may be ignored.

Second variant is internally translated into a call of this variant 'registerComponentImplementation(Object componentKey, Class componentImplementation)' which means the same type is used as the key to register the component with the Container. Another point to note here is that we didn't require to pass the parameter of type 'BankAccount' as it's already registered and the Container will pick that automatically. Moreover, as mentioned above the parameters passed serve just as hints and how many of them are treated (or ignored) by the Container depends on the particular implementation of the Container.


Once we have got the configured PicoContainer instance then we have used the getComponentInstance method (this method is a member of the PicoContainer interface and its signature is 'Object getComponentInstance(Object componentKey);' and it finds the component registered with the specified key) to fetch the well-built instances of the classes having all their dependencies injected into them. Notice that we have used 'DisplayAccountImpl.class' to fetch the instance of type 'DisplayAccountImpl' as we registered the instance with the same key.


Now we can use those instances as per the application requirements - in our case we are using the instance to call a public method named 'displayAccountDetails'.


The code-snippets listed above is just to give you an idea of how can we actually use a IoC Container to exploit the Constructor Injection feature. I've not compiled or tested the code. You may probably need to make some changes, but I suppose most of them would be cosmetic in nature.


Liked the article? You may like to Subscribe to this blog for regular updates. You may also like to follow the blog to manage the bookmark easily and to tell the world that you enjoy GeekExplains. You can find the 'Followers' widget in the rightmost sidebar.



Share/Save/Bookmark


Saturday, December 13, 2008

Spring: Beans, Container, Metadata, IoC Instantiation


Spring fwk: Beans, Containers, Configuration Metadata, IoC Instantiation

Beans - what are they and why do we call them beans?


Any object in your Spring application which is instantiated, assembled, and otherwise managed by the Spring IoC Container is called a Bean. Nothing special about these objects, except that the configuration metadata of the Spring framework contains details of these objects as how can they be instantiated and managed by the Spring IoC Container otherwise these objects are just like any other object used by your application.


Such objects were called Beans as the Spring framework was designed and developed in response to counter-attack the complexities of the Enterprise JavaBeans (EJB).


The Spring IoC Container


The central interface of the Spring IoC Container is BeanFactory, which is responsible for instantiating the application objects, configuring such objects, and managing the dependencies among these objects.


There are a number of implementations of this interface available today with one of the most popular being the XmlBeanFactory which allows the developers to specify the details of the object instantiation and their inter-dependencies in an XML File and the XmlBeanFactory takes care of interpreting the configuration XML metadata and subsequently providing a fully configured application taking the heavy load of object instantiation and inter-object dependency management off from the developers.


Configuration Metadata


This covers the details of object instantiation details of the application and also the details about inter-object dependencies. Depending on the form in which the metadata is supplied, the Spring framework would be required to use the corresponding type of IoC Container. The simplest and most popular form in which the metadata is supplied to the Spring framework is a simple and intuitive XML format. Evidently the XmlBeanFactory implementation of the BeanFactory interface is used as the Spring IoC Container in this case.


The other forms in which the configuration metadata can be supplied to the Spring framework are: using the Java Properties format, using Spring's public APIs to specify the metadata programmatically. Below is an image (taken from SpringFramework) which shows how all these pieces (POJOs, Config Metadata, and Container) magically fit together to produce a fully configured system ready to be used.

Pictorial representation of how the Spring Container magically produces a fully configured system ready to be used
Instantiating the Spring IoC Container


Not always you would be required to instantiate a Spring IoC Container explicitly like in case of a Web Application some 8 lines of boilerplate code written in the Web Descriptor file named web.xml will do that for us. Otherwise we would be required to write just a few lines explicitly to instantiate the Container.

Configuration Metadata files are passed to the BeanFactory or ApplicationContext constructors in form of objects of type Resource which encapsulates the metadata details as obtained from external resources like the local file system, from the Java CLASSPATH, etc.

Few examples of Container instantiation are:




Resource resource = new FileSystemResource("beans.xml");
BeanFactory beanFactory = new XmlBeanfactory(resource);

or

ClassPathResource classPathResource = new ClassPathResource("beans.xml");
BeanFactory beanFactory = new XmlBeanFactory(classPathResource);

or

String[] appContextResorce = new String[] {"applicationContext.xml", "applicationContext-part2.xml"};
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(appContextResource);
BeanFactory beanFactory = (BeanFactory)applicationContext;


Which all beans/objects will have their configuration details in the Spring configuration metadata?

Well... the configuration metadata needs to have the definition of at least one bean which the container would manage. How many other bean definitions would be captured by the configuration metadata, is something which depends upon your application requirements. Spring framework supports enormous possibilities and hence it's probably limited to your application requirements and your imagination.


Some of the common entries in the configuration metadata include service layer objects, DAOs, presentation layer objects such as Struts Action instances, infrastructure objects such as Hibernate SessionFactory instances, JMS Queue references, etc.


Liked the article? You may like to Subscribe to this blog for regular updates. You may also like to follow the blog to manage the bookmark easily and to tell the world that you enjoy GeekExplains. You can find the 'Followers' widget in the rightmost sidebar.



Share/Save/Bookmark


Tuesday, December 9, 2008

Spring: Inversion of Control, Dependency Injection


Spring IoC - Inversion of Control. DI - Dependency Injection.

Spring IoC - Inversion of Control

IoC pattern is defined as "A software design pattern and set of associated programming techniques in which the flow of control of a system is inverted in comparison to the traditional interaction mode." which means instead of the application calling the framework for services (as is the case with traditional patterns) it's the framework which calls the components as specified by the application.


DI - Dependency Injection


As you can deduce from the above para that IoC is quite generic in nature and perhaps not used by the Spring framework in entirety. The aspect of IoC used by the Spring framework is usually termed as DI or Dependency Injection as it focuses on injection of dependencies (required resources) into the dependent components at run time.

There are three main ways through which dependencies are injected into the dependent components. All these forms are supported in Spring either directly or indirectly. These forms are:

  • Constructor Injection - as the name suggests, in this form the dependencies are injected using a constructor and hence the constructor needs to have all the dependencies (either scalar values or object references) declared into it. Though, this form of DI is directly supported by the Spring IoC Container. But, Constructor Injection is mainly used by a highly embeddable, lightweight, and full-service IoC Container named PicoContainer. Read more about how do we actually code Constructor Injection using Pico in this article - Implementing CI using Pico. How CI works?
  • Setter/Mutator Injection - this form of DI uses the setter methods (also known as mutators) to inject the dependencies into the dependent components. Evidently all the dependent objects will have setter methods in their respective classes which would eventually be used by the Spring IoC container. This form of DI is also directly supported by Spring IoC Container. Though Spring framework supports both forms of DI namely the Constructor Injection and the Setter/Mutator Injection directly, but the IoC Container prefers the latter over the first.
  • Interface Injection - in this case any implementation of the interface can be injected and hence it's relatively complex than the other two where the objects of specified classes are injected. It's not supported directly by the Spring IoC Container. Interface Injection is used by The Apache Avalon. In 2004 Apache Avalon project closed after growing into several sub-projects including Excalibur, Loom, Metro, and Castle.

Setter vs Constructor Injection. Why Spring prefers the former?

  • Hard to manage a large number of constructor arguments: Spring framework prefers Setter/Mutator Injection over Constructor Injection because a large number of constructor arguments can become really hard to manage especially when many of them are optional. The Spring IoC Container will of course not have any such problem with Setter Injection type.
  • Re-injection or Amendment: One important thing to note here is that in case of Constructor Injection the dependencies are handed over at the time of object instantiation of the dependent objects whereas in case of Setter/Mutator Injection the dependencies are injected after the dependent object has already been created. Now if a re-injection or re-configuration of a dependent object is required , it can be easily done by calling the respective Setters in case of Setter Injection, but not the same in case of the Constructor Injection. So, should you need any re-configuration of the dependent objects, you would be better off with Setter Injection.

Why at all do we have Constructor Injection then?
Any real need?

Well... by saying that Spring IoC prefers Setter/Mutator Injection you should not deduce that the Constructor Injection has no real uses. Constructor Injection has its own benefit(s). This form of injection is preferred by the purists for the reason that the dependent objects are always handed over in a completely initialized state and no less than that. Right?


The obvious disadvantage in this case is that the dependent object becomes less flexible and hence any re-configuration becomes difficult.


How has the IoC pattern (or DI) been implemented in Spring framework?


Spring framework has two packages supporting this core functionality. These packages are: org.springframework.beans and org.springframework.context and the two interfaces which are the building blocks of Spring IoC are: BeanFactory and ApplicationContext.


ApplicationContext interface is actually a sub-interface of the BeanFactory interface. The top level interface, BeanFactory takes care of supporting an advanced configuration mechanism to manage objects of any type. ApplicationContext interface on the other hand is responsible for functionalities like integration to Spring AOP, message resource handling, event prorogation, and other enterprise-centric functionalities.

There are other specialized sub-interfaces as well which are targeted to add the specific set of functionalities on top of the the functionalities provided by ApplicationContext and BeanFactory interfaces. One such example is WebApplicationContext which is sub-interface of the ApplicationContext interafce and is responsible for providing enterprise-centric functionalities to be used in Web Applications.

Liked the article? You may like to Subscribe to this blog for regular updates. You may also like to follow the blog to manage the bookmark easily and to tell the world that you enjoy GeekExplains. You can find the 'Followers' widget in the rightmost sidebar.



Share/Save/Bookmark


Sunday, November 23, 2008

AspectJ, Aspect-Oriented Programming, Spring AOP


Aspect, AOP, AspectJ, Spring AOP, AspectJ vs Spring AOP

What's an Aspect? What's Aspect-Oriented Programming (AOP)?


An Aspect can be understood as a crosscutting concern which can not be covered by the usual grouping and abstraction mechanisms supported by the various programming methodologies. Why is that so? Because many concerns can cut across multiple abstractions as defined by the underlying program and hence the name 'crosscutting concern'. Right? To understand it better we can think of a simple example: In any typical Web Application (dealing with DB source) there are numerous occasions where we need to write code for opening a connection (or fetching a connection from a pool if we use Connection Pooling), defining a transaction to fire all the DML statements (contained in the transaction) in entirety and commit the changes or to simply rollback any changes made to the source in case even a single statement of the transaction fails. Now this transaction processing stuff can be thought of as an aspect and any developer using a typical programming language needs to code all the underlying stuff manually. Now, using AOP, this widely used crosscutting concern (as a typical programming abstraction can not be used for doing this directly) can be handled declaratively. This is just a sample example and the idea is to make you feel how easy (and hence fast-paced and robust) application programming can be by using this approach.


Logging is another stereo-type example of crosscutting concern widely used in almost every application. Why the developer should be bothered about coding/maintaining this using all the Logging classes/interfaces when s/he can do away with this by using an AOP in a declarative manner. As is the case with any other declarative code, this will also be translated back to the actual programming code and compiled thereafter, but who cares if all this is done behind the scenes. And not to forget that Translators/Compilers don't make mistakes while humans may (or should I say 'will' :-)) and hence using a declarative approach not only make the life simpler, but also improves the robustness of the entire application. Security is another very popular example of crosscutting concern which can effectively be handled using an AOP implementation.


Another great benefit of using AOP for such crosscutting concern implementation in an application is apparently visible if we need to change the underlying approach/considerations (say for example security considerations) then it might require a hell lot of effort to identify all the scattered code fragments doing the task and changing them to perform the new considerations/standards won't be easier either. Using AOP to handle such stuff will only require some declarative changes say for example it can be as simple as adding an advice and appropriate pointchecks.This will automatically check all such instances when any of the pointchecks match and in that case the advice will guarantee the execution of either the added security considerations or the changes ones. Wow, so easy? Yes, it is.


AspectJ - what's this?


It's an aspect-oriented extension to the Java programming language. The syntax is quite similar to that of Java and all the valid Java programs are valid AspectJ programs. But not the vice-versa as AspectJ supports many programming constructs alien to Java which are used to define and use aspects in applications. Eclipse Foundation first released this extension in 2001 and now it is available both as a stand-alone extension (pluggable to many popular frameworks) and integrated into Eclipse. AspectJ was originally developed by Gregor Kiczales and his team at Xerox PARC.
See below what Eclipse Foundation says about AspectJ:

What Eclipse Foundation says about AspectJ?
AspectJ is possibly the most generic and widely-used AOP extension and it focuses primarily on simplicity and usability. A Java-like syntax makes and availability of plug-ins for many popular frameworks make it even more popular with Java developers worldwide.


Some of the aspects which probably can not be defined by a typical programming language directly (not at least declaratively) and which can be easily achieved by using AspectJ are:

  • Ability to add members (methods of fields) within existing classes
  • Ability to define pointcuts when some method is called, some object is instantiated, etc.
  • Ability to run a piece of code before/after a pointcut is matched

Spring AOP. How is Spring AOP different from AspectJ?


Spring AOP is just another AOP implementation which comes with the Spring Framework bundle developed by SpringSource and released under Apache Licence 2.0.


Spring AOP differs from AspectJ probably in complexity and consequently in capabilities. Spring AOP implementation is less complex than the AspectJ implementation and hence less capable as compared to AspectJ. The main reason to keep Spring AOP simpler is because one of the foundation principles on which the Spring Framework was designed and developed is 'Simplicity'. In addition, Spring belives that most of the users don't really need those really complex features of AspectJ in their applications and hence Spring AOP would probably be more than sufficient for most of the application developers. In case there are a select few who want to use those missing features then they are most welcome to use AspectJ from within Spring Framework has support fro AspectJ since Spring 1.2 version itself and in every subsequent release they have continued making the integration even better. This will facilitate the developers to have the best of both the worlds. BTW, Spring AOP implementation is far more capable than it may sound here (only because it's being compared with the best of breed and de-facto AOP implementation named AspectJ) and the Spring Framework uses Spring AOP for transaction management, security handling, remote access, and JMX.


Liked the article? You may like to Subscribe to this blog for regular updates. You may also like to follow the blog to manage the bookmark easily and to tell the world that you enjoy GeekExplains. You can find the 'Followers' widget in the rightmost sidebar.



Share/Save/Bookmark