Sunday, March 27, 2016

React And React's Core Concepts



What is React?

React is known as the "V - View" in MVC, however, it is more appropriate to say that it comprises of the "V" and "C" in MVC. "V" and "C" stands for controller view, a controller view controls  other React components to work together.

React does not replace other frameworks such as, Angular or Knockout, that belongs to the view layer. React is just a Javascript library which allows us to create highly reusable UI components.  

What React Tries To Solve?

"Building large applications which data that changes overtime". In otherwords, you can build small to large applications which can change and manipulate the UI to reflect the current state of the app.

Why Choose React?

  • React is extremely fast so that it can detect changes in the app and manipulate the DOM , this is enabled by "Virtual DOM", we'll discuss which a bit later.
  • You can create custom UI components, even nest components and pass data from parent to child components. For example, think of "Comment Box" as parent component and "Comment Form" as child component of comment box.
  • React is easy to integrate with existing applications, the best part is that you can gradually change your existing application without having to change your application overnight.
  • Isomorphic a term which is very hot in React community, Isomorphic means that you can render your components in client and server so that you can avoid repeating your code twice.
  • React has a proven track record of use, as it has been used by Facebook, Instagram, Airbnb and many other large corporations.
Okay, it enough knowing the Why part of React, let's jump into it's core concepts.

React's Core Concepts

This is the second part of this post, this section would highlight and introduce you to React's core concepts.

Unidirectional Data Flow

Unidirectional data flow is a pattern where the applications data flow is handled as one-way data binding, unlike other popular frameworks such as Angular which follows two way data binding.

If you have experimented with Angular or any other frameworks with deals with two way data binding you will understand that two data binding is all about updating your UI as the model changes or update your model as the UI changes. However, along with the benefits it also introduced to certain risks related to data flow in your application as follows:
  1. This lead to unpredictability, it means that if the UI changes it will change the related model and if this model is connected to another model it would change that too. This was totally, unpredictable for the developer.
  2. Moreover, the above mentioned problem can make debugging much more harder and which makes it harder to find the root cause of the problem.
Flux is an architecture that follows unidirectional data flow pattern. Facebook has it's own implementation of flux and also there other flavors of flux such as Redux. If your are interested in Redux go and check out Egghead.io's coures on Redux

There are three main concepts that are must to be know to use Flux and they are:
  1. Action
  2. Dispatcher 
  3. Store
This image from Flux's official website will help you to understand what are these three flux concepts.

Flux Architecture



JSX 

JSX is also called as "HTML in Javascript", it is important to note here that it is not the real HTML, it is identical to HTML syntax. For example, we have the class attribute in HTML, in JSX it is called as className. All this time we have been writing "Javascript in HTML", with JSX it's the vice versa.

Moreover, Javascript is more powerful than HTML, so that use can use all of Javascript features in HTML. 

JSX complies to plain Javascript, JSX is mere an abstraction to plain Javascript. JSX is optional, you have a choice to make here, Javascript or JSX? 

JSX has an awesome error location finder feature, it will show you the exact line the application error occurred which was not present in HTML. 

Having used JSX, I personally recommend to use JSX over plain Javascript for two main reason, easier to write - just like HTML and less prone to typos and it is more readable

Virtual DOM

Virtual DOM is one of the cool concept or feature of React that I love about. So what is it all about? 
Virtual DOM is where the current state of the DOM is compared against with the desired or expected state of DOM and it is updated in a most efficient manner.

Updating the DOM involves a lot of processing and then re-drawing the UI elements. This the main reason why React had to introduce Virtual DOM.

Virtual DOM is not only performance booster but it also includes flexibility.


Further References and Tutorials




Wednesday, February 24, 2016

How to overcome "FAILURE"?


I've been away from my blog for a prolonged period of 3 months and this will be my first post for 2016. Every time I think of writing a new post to my blog, I FAIL in that task very badly.

Failing to do a task has many number of reasons, here are some reasons:
  • Laziness
  • Lack of Persistence
  • Negative Self Talks
Laziness has overcome many of us. For example, going for a morning walk can be a daunting task to some people, while others enjoy the benefits of relaxation and peace of mind gained through this routine walk.

Laziness is a root cause for us to NOT achieve our own goals. If we are able to beat and overcome laziness we can achieve more from the 24 hour day, hence becoming more efficient and effective. If you want to learn more about How to beat Laziness, there is a blog post written just for you.

How many of us have started a particular task and then left that task uncompleted? Task after task are uncompleted, the list of uncompleted tasks overweights the list of completed task.

This is mainly because Lack of Persistence in a given task. Take the earlier example of routine morning walk, how long do many of us continue walking every day in morning no matter what the outcomes are? Very few are continuously successful in this endeavor. 

Pushing yourself forward is the way to avoid lack of persistence. How hard it becomes, you just keep moving forward. Day after day, the task will be easier to do and even can become more enjoyable.

J.K. Rowling had to go twelve publishers to publish here first book, many of us can barely write a book to publish and if we write a book, we would have lacked motivation by going to three or four publishers but she kept moving forward and saw the results.

I want to include another example, Thomas Edison - Inventor of light bulb, failed 1000 times in the invention of the light bulb, if he would have stopped then he wouldn't have go the title of Inventor and someone else would have invented it. 

You learn by failing, fail but never give up until you've achieved your goal. 




Can I write a blog post? I don't have the skill of writing? My language is not good enough? Hmm, do you get this negative self talks when you're asked to write a blog post or an article? 

Well, this is just a mere imagination of your mind, this is NOT the reality. We are fearful by just imagining the outcome instead of just start to write the blog. Yes, sometimes you will suck at this point, but never loose confidence in yourself, just continue and look back what you have got once you've finished writing the blog or article. It will be a self accomplishment for you to do more of this in the future. 

Believe in yourself first, work hard toward achieving your goals then success will follow you.





Friday, November 20, 2015

AngularJS and SPAs




AngularJS is MVW or MV*  or MVVM framework to develop large scale enterprise applications. AngularJS is a buzz word for modern web developers and some business specifically hire AngularJS developers.

It has made the front-end web development easier than ever with loads of cool features.

What does MVW means?


MVW - Model View Whatever. "Whatever" can thought as "Controller" in MVC, but in AngularJS this does mean that,

Whatever = Watch and Digest Loop in AngularJS

Here are some good resources to learn more about Watch and Digest Loop:

Benefits of SPAs

We can move around the web site without reloading it, just like our old school standalone desktop apps. AngularJS uses the hash or the pound symbol (#) to build up SPAs.


Let's look how we can build Single Page Application using AngularJS


Project Directory





angularmain.js

 
var firstApp = angular.module('firstApp', ['ngRoute']);

//route configurations
firstApp.config(function ($routeProvider) {
    $routeProvider
        .when('/', {
            templateUrl: 'webpages/home.html',
            controller: 'homeController',
        })
        .when('/about', {
            templateUrl: 'webpages/about.html',
            controller: 'aboutController',
        });
});


// controllers
firstApp.controller('homeController', ['$scope', function ($scope) {

    $scope.name = 'From Home Controller';

}]);

firstApp.controller('aboutController', ['$scope', function ($scope) {

    $scope.name = 'From About Controller';


}]);

firstApp.controller('mainController', ['$scope', '$location', function ($scope, $location) {

    // sets the active style for the navbar elements
    $scope.isActive = function (viewLocation) {
        return viewLocation === $location.path();
    };

}]);

Angular module is a where angular is initialized. Route Configurations enables us to implement SPAs where we are specifying the url, templateUrl - physical location of the webpage for the url, and it's associated controller.

In our example, "/" refers to the home or the index page which is the url, 'webpages/home.html' the home.html is located inside of webpages folder and "homeController" is it's controller responsible for it.

The scope object is only visible to it's respective controller. Ex: $scope.name in homeController and aboutController are different.


template.html

 
<!DOCTYPE html>
<html lang="en" ng-app="firstApp">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>AngularJS and SPAs</title>

    <!-- Bootstrap -->
    <link href="css/bootstrap.min.css" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>

<body>
    <nav class="navbar navbar-default">
        <div class="container-fluid">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#app1" aria-expanded="false">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="#/">
                    <span>AngularJS and SPAs</span>
                </a>
            </div>
            <div class="collapse navbar-collapse" id="app1" ng-controller="mainController">
                <ul class="nav navbar-nav navbar-left">
                    <li ng-class="{ active: isActive('/')}"><a href="#/">Home</a></li>
                    <li ng-class="{ active: isActive('/about')}"><a href="#/about">About</a></li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container" ng-controller="homeController">
        <div class="row">
            <div ng-view></div>
        </div>
    </div>


    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/bootstrap.min.js"></script>

    <!-- AngularJS Scripts -->
    <script src="//code.angularjs.org/1.4.7/angular.min.js"></script>
    <script src="//code.angularjs.org/1.4.7/angular-route.min.js"></script>

    <!-- External JS -->
    <script src="js/angularmain.js"></script>

</body>
</html>
The index page serves as the template page for the application. There are three AngularJS "custom attributes" used here:

  • ng-app - Specifies the angular module
  • ng-controller - the controller for the index page and what page of the page will it                            control
  • ng-view - This takes the view from the angular route configurations

home.html

 
<div class="form-group">
  <label for="inputBox">Text from Controller </label>
  <input type="text" class="form-control" id="inputBox" ng-model="name">
</div>
 
Gets the ng-model from the "homeController", ng-model is an angular directive and it is two way binding element. The term two way binding means that when the HTML is changed it automatically changes the Javascript and vice-versa.


about.html

 
<div class="form-group">
    <label for="inputBox">Text from Controller </label>
    <input type="text" class="form-control" id="inputBox" ng-model="name">
</div>
 


Final Result


Home Page

About Page


Further References and Tutorials



Sunday, October 11, 2015

Basic Spring Web Application

In this tutorial we are going to build a basic Spring Web App, that will output Hello World!
I'm going to split this tutorial into four separate sub-sections, so that it'll be easily to follow on. I would manually change a Dynamic Web Project into a Maven Web Project.  

Setting up your project

 Create the Dynamic Web Project and tick the check box "Generate Deployment Descriptor". This is how your project directory will look like.

 Next, convert your Web Project into a Maven Project. Select the project directory and right click, and follow the image below.

 
Web Project convert to Maven Project

POM.XML file creation
 Specify, the group id and the artifact id for the pom.xml file. You can type your own names for the group id and the artifact id. After the creation of the pom.xml file your can see it listed on the project directory.

I assume that the Spring IDE and the Maven Integration for Eclipse plugins are installed in Eclipse.

Open the POM.XML file and go to "Dependencies" tab and click on "Add" to add maven dependencies to your project. For some reason you cannot search for maven dependencies. So you'll have to do the log way. 

Go to http://mvnrepository.com/ and search and add the below mentioned dependencies.
  • Spring-core 3.2.3.RELEASE
  • Spring-beans 3.2.3.RELEASE
  • Spring-context 3.2.3.RELEASE
  • Spring-web 3.2.3.RELEASE
  • Spring-webmvc 3.2.3.RELEASE
 
 
Adding spirng-core dependency using pom.xml interface

 After adding all the dependencies, right click the project, go to Maven tab and click on "Update Project".

Project directory after adding all the dependencies

 Some dependencies were previous downloaded, that's the reason it's being listed on to the above project directory.

 Sometimes, Eclipse removes maven dependency path from the deployment assembly, we need maven directory in our deployment assembly. To do this, right click on the project, go to properties section and browse to "Deployment Assembly" tab and click on "Add" and click on "Java Build Path Entries" and "Maven Dependencies".

Web Deployment Assembly after adding the Maven Dependency Path

Adding a Dispatcher Servlet


A dispatcher servlet takes the incoming requests and finds the appropriate handler to handle that particular request and to return a response to the user. The dispatcher servlet sits in between the user's request and the controller.


Let's get up and code, to add the dispatcher servlet to the project do the following steps:

  1. Select the project and add a new servlet. Do not forget to tick the checkbox "Use an existing Servlet class or JSP".


To use the class DispatcherServlet we need to have the spring-webmvc maven dependency.

    2. Open the web.xml file set the display name, servlet name, url pattern and configure the load on startup.


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>WebApp</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>school</display-name>
    <servlet-name>school</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>
 <load-on-startup>1</load-on-startup>
  <servlet-mapping>
    <servlet-name>school</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

  • Load on startup - We have to specify load on startup, to load this dispatcher servlet on startup. It takes in integer values starting, value 0 has the highest priority. 

     
    3. Create a spring bean configuration file that contains all the configurations for Spring MVC.This can handle web requests, data binding, request mapping and view resolving. Note that this file should be created under the WEB-INF directory and must follow a pattern like : nameOfDispatcherServlet-servlet.xml

Spring Bean Configuration File

Adding a Controller

Here are the steps to add and configure the controller.

          1. Add a controller class under the java resources directory. Give it a package name and a class name.



          2. Say the controller to return the index page if the request is the context path(/). 

package com.kasibsblog.spring.web.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class SchoolController {
@RequestMapping("/")
public String showIndexPage(){
return "index";
}

}

The "Controller" annotation specifies that this class in a controller class, "RequestMapping" specifies what view to return for specific user request.

In our example, the showIndexPage() method returns the index page if we go to the project root, that is "/" .


          3. Load the controller package to the spring bean configuration context file - school-context.xml
         


Add the context and mvc namespace in the Namespaces tab in school-context.xml file.



Go to the "Context" tab and add the annotation config element and the component scan element, in component scan add the package name of the controller class to the base package attribute. 

This adds the controller class to the Spring context configuration file. Finally, to finish of this section, open up the "MVC" tab and add the mvc-annotation-driven element. This is needed for the "Controller" annotation to work.



Your school-context.xml file source will look like,



Adding a View 

        1. Create a folder under WEB-INF folder, called as jsps. Add a new jsp file to the jsps folder and name the jsp file as index.jsp. Type the text "Hello World Index Page!!"



index.jsp page

          2. Now, create a View Resolver bean in the school-servlet.xml file. 



This creates a new bean with id "jspViewResolver" you can give your own id, class should be "InternalResourceViewResolver". Check the above image for the fully qualified name.

          3. Add the prefix and suffix properties for the jspViewResolver bean and set it's values.

adding a bean property element

adding prefix  property

suffix property

We are almost finished, to make sure every thing is working correctly, run the application and it should return a page like this: 




Congratulations, you've successfully completed a basic Spring MVC Web application. 


























Tuesday, September 15, 2015

Autowiring using Annotations





In one of my previous post I talked about XML based autowiring. Was it a hassel to configure it? If yes, then we'll look an easier way to our autowire the beans - Autowiring using Annotation.

Autowiring using Annotation can be done using several annotation methods, they are :
  • Autowired
  • Resource
  • Inject

Here we are going to discuss Autowired annotation and some other annotations. 

What's this annotation?

Annotation is a like a specifier and there are many annotations specifiers provided by Java. A basic annotation can be "@Override" specifier. 


Setting up annotation 

 

View the classes, interfaces and the XML configuration files used in this example

 

To use the annotation we'll need to add the following code to the existing configuration file. 

This code should be added to the beans tag as follows:

xmlns:context="http://www.springframework.org/schema/context"

This adds the context namespace to the XML file.

The schema location parameter too needs to be changed as follows: 

xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"

The section which is highlighted is the new addition to the schema location parameter.

Finally, this last piece of code is also required to set up annotations successfully.

<context:annotation-config></context:annotation-config>

It should be added in between the beans tag.

 

Autowired Annotation

 

Here comes the long awaited section, using annotation we can reduce the XML configuration time and it's some times boring for developers to configure things up. Now let's go to the code.

package com.kasibsblog.spring.test;

import org.springframework.beans.factory.annotation.Autowired;

public class AbCompany {

    private FullTimeEmployee fulltime;
    private PartTimeEmployee parttime;

    @Autowired
    public void setFulltime(FullTimeEmployee fulltime) {
        this.fulltime = fulltime;
    }

    @Autowired
    public void setParttime(PartTimeEmployee parttime) {
        this.parttime = parttime;
    }

    public void printFullTime(String name, int salary, String company) {
        fulltime.print(name, salary, company);
    }

    public void printPartTime(String name, int salary, String company) {
        parttime.print(name, salary, company);
    }

    
In the above example, the autowired annotation is placed before the setter method, this is one way of placing the autowired annotation. We can even set the annotation to only the properties, constructor or we can mix the setter methods, properties and/or the constructor. Even we can eliminate the setter methods and constructor.

Now, we'll look how we can mix single argument constructor with a property.

 
package com.kasibsblog.spring.test;
import org.springframework.beans.factory.annotation.Autowired;


public class AbCompany {
     

    @Autowired
    private FullTimeEmployee fulltime;
    private PartTimeEmployee parttime;


    @Autowired
    public AbCompany(PartTimeEmployee parttime){
        this.partttime = parttime;
    }
    public void printFullTime(String name, int salary, String company) {
        fulltime.print(name, salary, company);
    }

    public void printPartTime(String name, int salary, String company) {
        parttime.print(name, salary, company);
    }

 

 

 



Wednesday, September 9, 2015

How to deal with Ambiguities in Autowiring - Spring

In the last post - Autowiring in Spring we discussed Autowirirng and different methods of doing it. Also I gave an introduction to ambiguities in autowiring, so this tutorial is a continuation of it. 

Here I will discuss two other ways we can deal with the ambiguity in autowiring.

1. Autowiring Candidate property


 Autowiring candidate is a way to turn on or turn off autowiring of a bean and it is set per bean. Autowiring-candidate property has several choices : 
  • true - If it is set to true, then it can wire with the other bean.
  • false - If it is set to false, then it autowiring is totally prohibited.
  • default -  This is the default value set and can be considered to autowire.
Now, let's look at our sample code.

<?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:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"
    default-autowire="byType">

    <bean id="abcompany" class="com.kasibsblog.spring.test.AbCompany">
    </bean>

    <bean name="parttime" class="com.kasibsblog.spring.test.PartTimeEmployee">
    </bean>
   
    <bean name="parttime2"
        class="com.kasibsblog.spring.test.PartTimeEmployee"
        autowire-candidate="false">
    </bean>

    <bean name="fulltime"
        class="com.kasibsblog.spring.test.FullTimeEmployee">

</bean>
</beans>


The bean with id - parttime2, cannot be autowired and it is prohibited. If the autowire-candidate property was set to either default or true, the program will throw an exception as the autowiring method is set to byType.



2. Primary property

 

Primary property is another technique to overcome ambiguity in autowiring. We can set the primary property to either true or false. Unlike the autowiring-candidate property set to false, primary does not totally prohibit it from autowiring only the preference level is set by it.

Let me now explain this by an example,

<?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:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"
    default-autowire="byType">

    <bean id="abcompany" class="com.kasibsblog.spring.test.AbCompany">
    </bean>

    <bean name="parttime" class="com.kasibsblog.spring.test.PartTimeEmployee">
    </bean>
   
    <bean name="parttime2"
        class="com.kasibsblog.spring.test.PartTimeEmployee"
        autowire-candidate="false">
    </bean>

    <bean name="fulltime"
        class="com.kasibsblog.spring.test.FullTimeEmployee"

        primary="true">
</bean>

<bean name="fulltime2"
        class="com.kasibsblog.spring.test.FullTimeEmployee">

</bean>
</beans>

In the above sample code, we have two beans of type - FullTimeEmploye, I had set the bean - fulltime to be my primary bean to autowire. This does not mean that fulltime2 is totally prohibited from autowiring. It can be autowired with other beans.

 

Tuesday, September 8, 2015

Autowiring in Spring

Autowiring is a technique to wire the beans together. Specially, when there are many dependencies, all of the dependencies can be  managed easily using Autowiring.

Autowiring can be performed in several methods, here are the following methods it can be done:
  1. byType
  2. byName
  3. constructor
  4. default
We can use the autowiring property of the bean to set the autowiring method.

In this example we are going to use the following classes, interface and XML file.

Employee - Interface

package com.kasibsblog.spring.test;

public interface Employee {
   
    public void print(String name, int salary, String company);

}

FullTimeEmployee - Class

package com.kasibsblog.spring.test;

public class FullTimeEmployee implements Employee {

    public void print(String name, int salary, String company) {
        System.out.println("Company : " + company + ", " + "Name : " + name + ", " + "Salary : " + salary + ",  "+ "Type : Full-Time");
    }

}

PartTimeEmployee - Class

package com.kasibsblog.spring.test;

public class PartTimeEmployee implements Employee {

    public void print(String name, int salary, String company) {
        System.out.println("Company : " + company + ", " + "Name : " + name + ", " + "Salary : " + salary + ", "
                + "Type : Part-Time");
    }
}

AbCompany - Class

package com.kasibsblog.spring.test;

public class AbCompany {

    private FullTimeEmployee fulltime;
    private PartTimeEmployee parttime;
 
    public void setFulltime(FullTimeEmployee fulltime) {
        this.fulltime = fulltime;
    }

    public void setParttime(PartTimeEmployee parttime) {
        this.parttime = parttime;
    }
   
    public void printFullTime(String name, int salary, String company){
        fulltime.print(name, salary, company);
    }
   
    public void printPartTime(String name, int salary, String company){
        parttime.print(name, salary, company);
    }

}

Main - Class

package com.kasibsblog.spring.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {

    public static void main(String[] args) {

        ApplicationContext context = new ClassPathXmlApplicationContext("com/kasibsblog/spring/test/beans/beans.xml");
       
        AbCompany abcompany= (AbCompany) context.getBean("abcompany");
        abcompany.printFullTime("Sue", 12000, "Ab Company");
        abcompany.printPartTime("Mary", 10000, "Ab Company");

        ((ClassPathXmlApplicationContext) context).close();
    }

}

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"
    default-init-method="init" default-destroy-method="destroy"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">


    <bean id="abcompany" class="com.kasibsblog.spring.test.AbCompany">
    </bean>

    <bean id="partTime" class="com.kasibsblog.spring.test.PartTimeEmployee">
    </bean>
   
    <bean id="fullTime" class="com.kasibsblog.spring.test.FullTimeEmployee">
    </bean>

</beans>

Now let's look at different modes of autowiring.

1. byType

Autowiring is done by using the data-type. It tries to match exactly a bean per data-type, if it finds more than a bean of the same type then an exception is thrown, also known as "Autowiring ambiguity".

  <bean id="abcompany" class="com.kasibsblog.spring.test.AbCompany" autowiring="byType">
  </bean>

 Assume that there are two beans of FullTimeEmployee as:

<bean id="fullTime" class="com.kasibsblog.spring.test.FullTimeEmployee">
</bean>

<bean id="fullTime2" class="com.kasibsblog.spring.test.FullTimeEmployee">
 </bean>

In this case, an exception would be thrown.

2. byName

Autowiring byName uses the the bean name or the bean id to wire the beans together.

<bean id="abcompany" class="com.kasibsblog.spring.test.AbCompany" autowiring="byName">
</bean>

<bean id="fullTime" class="com.kasibsblog.spring.test.FullTimeEmployee">
</bean>

<bean name="partTime" class="com.kasibsblog.spring.test.PartTimeEmployee">
</bean>

3. constructor

<bean id="abcompany" class="com.kasibsblog.spring.test.AbCompany" autowiring="constructor">
</bean>

The abcompany bean autowiring property is now set to constructor. The ABCompany class should include a two argument constructor, for this example.

public AbCompany(FullTimeEmployee fulltime, PartTimeEmployee parttime){
        this.fulltime = fulltime;
        this.parttime = parttime;
    }

The beans should match both the arguments specified in the in the constructor, otherwise it will thrown an error.

Assume that the bean with id - fulltime, has the class set to AbCompany. This will result an ambiguity as the abcompany been autowired by constructor.

<bean id="fullTime" class="com.kasibsblog.spring.test.AbCompany">
</bean>

4. default

Spring allows us to set a default autowiring which will be activated for the specified XML configuration file.

The default autowiring should be added to the beans tag in the configuration file, not the bean tag

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

</beans>

In the above sample code, I have selected the default autowiring method as byType. We can also specify any one of the above discussed methods.

Moreover, assume that there are two beans that belongs to FullTimeEmployee class. For example,

<bean name="fulltime" class="com.kasibsblog.spring.test.FullTimeEmployee">
 </bean>

<bean name="fulltime2" class="com.kasibsblog.spring.test.FullTimeEmployee">
</bean>

In this case, an exception would be thrown since that Spring cannot detect which bean to select from the two beans. In order to eliminate this ambiguity we can specify what bean should be used to wire with the "abcompany" bean.

We can achieve this by using the default-autowing-candidates property of the beans tag.

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"
    default-autowire="byType" default-autowire-candidates="fulltime,parttime">

</beans>

Here the fulltime and partime beans areselected as the default-autowire-candidates. It is a comma seperated list also note that the list cannot contain any white spaces.

Using wildcards to specify default-autowire-candidates

Wildcards can be used to specify the default candidates, an asterisk(*) is used as the wildcard character.

In our example, both the beans end with "time" - fulltime & parttime. The code can be changed to 

default-autowire-candidates="*time"