1. Node Package manager is a package manager which ships along node
  2. It is a Javascript package manager which helps to manage modules like HTTP, Event etc..
  3. Once the npm init is run package.json would be created in the project folder.It is similar to pom.xml for Maven project which saves all the settings and dependencies
  4. To check the npm version
    >>npm -v 
    >>npm --version
    
  5. To create a new project we use the below command – take default setting by telling -yes
    >>npm init -yes
    
  6. To Install a new package is as below
    >>npm install NAME_OF_PACKAGE
    
  7. To Set particular config name
    >>npm set CONFIG_KEY CONFIG_VALUE
    >>npm set init-licencse "MIT"
    
  8. To Get particular config name
    >>npm get CONFIG_KEY 
    >>npm get init-licencse
    
  9. To Install a new package
    >>npm install packagename
    >>npm install loadash
    

    Running the above command is going to create a node_modules folder in project with the dependencies for the package(loadash) installed.

  10. To Install only dependencies that are needed to run app other than utility dependencies like gulp which provides minified version of JS use below command
    >>npm install --production
    
  11. To remove dependencies
    >>npm remove gulp
    
  12. To install specific version
    >>npm install gulp@4.7.3
    
  13. To update latest version
    >>npm update gulp
    
  14. Semantic versioning formart.PatchVersion includes bug fixes and minor tweaks
    MajorVersion.MinorVersion.PatchVersion
    4.7.8
    
  15. How to find the location of node modules
    >>npm root -g
    

    This will take you to location C:\Users\Mugil\AppData\Roaming\npm\node_modules

  16. How to install server globally – live-server will reload the JS files without restart of server
    >>npm install -g live-server
    

    This will take you to location C:\Users\Mugil\AppData\Roaming\npm\node_modules

  17. When you move the project to new environment no need to move the node_modules folder similar to avoiding JAR while shifting java application.We just need to move the JS file and package.json which contains the details of dependencies. Running npm install will read the package.json file and load the dependencies in new environment

package.json

   "name": "my_package",
    "description": "",
    "version": "1.0.0",
    "main": "index.js",
    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1"
    },
    "dependencies": {"loadash" : 14.7.8},
    "keywords": [],
    "author": "",
    "license": "ISC",
    "bugs": {
      "url": "https://github.com/ashleygwilliams/my_package/issues"
    },
    "homepage": "https://github.com/ashleygwilliams/my_package"
  }

How to run some js file in the beginning of the server
I have JS server which needs to start at the beginning of application. In such case I would be defining the JS file in scripts.
You need to call npm start after chaning package.json file
package.json

.
.
"scripts": {
      "start": "node server.js"
    }
.
.

Let’s create a simple application which greets with Welcome message in console on start
package.json

{
  "name": "school",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  },
  "author": "Mugil",
  "license": "ISC"
}

index.js

console.log('Welcome to School .....');

output

Welcome to School .....

package.json
live-server allows you to run code without restarting server after changes.

.
.
"scripts": {
    "start": "node index.js",
    "server": "live-server"
  }
.
.
>>npm run server
  1. Obersvable and Observer are from RxJS similiar to Event and Event listener
  2. Observer can listen to three actions of observable that is next, error and complete
  3. Below we create a observer JSON key value pair and calling function based on the action from observable
  4. We need to subscribe to Observable in ourcase observable and pass observer as parameter
  5. We should unsubscribe to obeservable once we are done inorder to prevent memory leaks

test.html

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.4.0/Rx.js"></script>

    <script>
        var observer = {
            next: function (value) { console.log(value); },
            error: function (error) { console.log(error); },
            complete: function () { console.log("Completed..!") }
        };


        const observable = new Rx.Observable(obs => {
            obs.next(102);
            obs.next(103);
            setTimeout(function () {
                obs.next(109);
                obs.complete("Completed");
            }, 2000);
        });

        observable.subscribe(observer);
    </script>

Observable over Stream
Observable is similar to event which keeps happening. During its occurance it could emit values, throw error or comes to complete.

setTimeout is the functionality which comes along with the webapi whereas setInterval is javascript implementation.

setTimeout(expression, timeout); runs the code/function once after the timeout.
The clearTimeout() method stops the execution of the function specified in setTimeout().

function doStuff() {
alert("run your code here when time interval is reached");
}
var myTimer = setTimeout(doStuff, 5000);

Output

run your code here when time interval is reached

setInterval(expression, timeout); runs the code/function in intervals, with the length of the timeout between them.

function doStuff() {
alert("run your code here when time interval is reached");
}
var myTimer = setInterval(doStuff, 5000);

Output

run your code here when time interval is reached

JWT can be implemented the same way for OAuth where the authorization server and the resource server are different. In this scenario Authorization server provides just the token and exposes JWK(JSON web keyset) for its public key.

JWT always deals with Authorization, not Authentication.

  1. User logins to application – Authentication to the user-facing application
  2. Once authenticated, User can request access to any resource.
  3. User-facing application can request an access token that will serve to request the external resource in representation of the end user, so the resource server can determine who is requesting the information (authentication) and the access level of that user (authorization). On this step an Oauth2 Access token request is performed
  4. Authorization server will validate the request for an access token. The end-user application can provide client credentials to prove identity of the invoker, as well as a hint to determine the user who triggers the process.

    Authorization server to generate a new RSA key pair, whose private key will be utilized to create the JWT signature, while the public key will be stored and published so any resource server who receives the JWT can look up the public key and perform signature verification.

  5. User-facing application receives the JWT access token, attaches it to a new HTTP request as an Authorization header, as a bearer token, and invokes the resource server to attempt the retrieval of the external resource.
  6. Resource server detects that a Bearer token was included in the new request received, decodes the header in order to find out the JWK key id, then connects to the authorization server JWK set URL in order to retrieve the list of available public keys, then filters the key with id indicated in the header. Once the JWK is found, Resource server just must perform signature verification to determine if the JWT received is valid
  7. Once JWT is verified, the payload is considered as valid, and any information within the payload can be used by the resource server to determine whether the requested resource can be delivered in the request received or not.

Advantage of Using Asymmetric Keys
In a microservice architecture where JWTs are exchanged, each service can have a public/private key pair. Compared to symmetric signatures, this scheme significantly reduces the impact of a breach of a single service in this architecture.

Posted in JWT.

What is the difference between a shim and a polyfill?
Shim
A piece of code that you could add (i.e. JavaScript) that would fix some functionality, but it would most often have it’s own API.Shims intercepts API calls and creates an abstract layer between the caller and the target. Typically shims are used for backward compability. For instance the es5-shim npm package will let you write ECMAScript 5 (ES5) syntax and not care if the browser is running ES5 or not. Take Date.now as an example. This is a new function in ES5 where the syntax in ES3 would be new Date().getTime(). If you use the es5-shim you can write Date.now and if the browser you’re running in supports ES5 it will just run. However, if the browser is running the ES3 engine es5-shim will intercept the call to Date.now and just return new Date().getTime() instead. This interception is called shimming. The relevant source code from es5-shim looks like this:

polyfill
something you could drop in (i.e. JavaScript) and it would silently work to mimic existing browser APIs that are otherwise unsupported.A polyfill is a piece of code (or plugin) that provides the technology that you, the developer, expect the browser to provide natively. Flattening the API landscape if you will.A polyfill is a type of shim that retrofits legacy browsers with modern HTML5/CSS3 features usually using Javascript or Flash.Polyfill is about implementing missing features in an API, whereas a shim wouldn’t necessarily be as much about implementing missing features as it is about correcting features. As an example there is no support for sessionStorage in IE7, but the polyfill in the sessionstorage npm package will add this feature in IE7 (and older) by using techniques like storing data in the name property of the window or by using cookies.

Code Snippets – Table of Contents

  1. Builtin Angular Directives

    1. Attribute Directive – NgStyle, NgClass
    2. Structural Directive – *NgIf, *NgFor, *NgSwitch

Attribute Directive – ngClass and ngStyle
ngClass

  1. For using ngClass the styling should be in JSON Obect
  2. Advantage of using ngClass is applying more than one class to the DOM Element unlike class
  3. In the below code you see class which applies present or absent based on one true or false returned by getResult function
  4. In the registration.component.ts we have declared a JSON object which applies 2 classes present and normal or absent and bold based on true or false returned by getStatus(method)

Styling using class
registration.component.html

.
.
<td [class]="getStatus()?'present':'absent'">{{objStudent.science}}</td>
.
.
.

Styling using ngClass
registration.component.html

.
.
<td [ngclass]="cssStyle">{{objStudent.science}}</td>
.
.
.

registration.component.ts

.
.
export class RegistrationComponent implements OnInit { 
  public cssStyle;  
 
  ngOnInit() {
     this.cssStyle = {
       "present" : getStatus(),
       "absent"  : !getStatus(),
       "normal"  : getStatus()
       "bold"    : !getStatus(),       
     };
  }
}

.
.
.

ngStyle

  1. ngStyle is to apply style directly instead of defining style using class
  2. Same registration.component.ts has been modified to take style attributed such as color and weight

registration.component.ts

.
.
export class RegistrationComponent implements OnInit { 
  public cssStyle;  
 
  ngOnInit() {
     this.cssStyle = {
       "background-color"  : getStatus()?"green":"red",
       "font-weight"       : getStatus()?"normal":"bold"       
     };
  }
}
.
.
.

There is an alternative for both above [class] and [ngClass] as below

.
.
<td [class.positive]="getStatus()" [class.negative]="!getStatus()">{{objStudent.science}}</td>.
.

Similarly for [ngStyle] as below

.
.
<td [style.background-color]="getStatus()?'green':'red'">{{objStudent.science}}</td>.
.

Structural Directive – ngIf, ngFor and ngSwitch
ngIf

  1. In the below code we decide the words to be displayed based on the value returned by getStatus(objStudent) method
  2. Pass would be displayed if true or else fail would be returned
.
.
<span *ngIf="getStatus(objStudent)">Pass</span>
<span *ngIf="!getStatus(objStudent)">Fail</span>
.

ngFor

  1. In the below code we use *ngFor loop to iterate over array of student object
  2. We are generating serial no for first column by adding 1 to variable i and displaying name of student in second column
  3. *ngFor has other loacl values apart from indes such as even, odd, first, last based on which manipulations could be carried out

registration.component.ts

.
.
export class RegistrationComponent implements OnInit {
  public arrStudent:Array<Student>;

  ngOnInit() {
     this.arrStudent = [new Student(101, 'Mugil', 31, 74, 65,55,64,84),
                        new Student(102, 'Manasa', 26, 31, 65,55,86,84),
                        new Student(103, 'Kavitha', 27, 90, 65,60,84,46),
                        new Student(104, 'Renu', 28, 31, 65,55,84,46),
                        new Student(105, 'Joseph', 23, 31, 65,55,89,84)];

  }
.
.
}

registration.component.ts

.
.
<tr>
    <th>Sno</th>
    <th>Student ID</th>
</tr>
<tbody>
  <tr *ngFor="let objStudent of arrStudent; index as i;">
     <td>{{i+1}}</td>
     <td>{{objStudent.studentId}}</td>
     .
     .
     .
     .
  </tr>
</tbody>
.
.

Now let’s see a simple example of applying a different color to text based on odd and even rows

registration.component.ts

.
.
<tr *ngFor="let objStudent of arrStudent; index as i;odd as isOdd; even as isEven" [class]="isOdd?'odd':'even'">
     .
     <td>{{i+1}}</td>
     <td>{{objStudent.studentId}}</td>
     .
</tr>

the same code can be written as below where the only difference is styles are applied seperately evaluating for both odd and even.
registration.component.ts

.
.
<tr *ngFor="let objStudent of arrStudent; index as i;odd as isOdd; even as isEven" [class]="isOdd" [class.even]="isEven">
     .
     <td>{{i+1}}</td>
     <td>{{objStudent.studentId}}</td>
     .
</tr>

We can define the template directly in a component instead of giving the templateURL using a template and define styleURL instead of styles.

registration.component.ts

.
.
@Component({
  selector: 'app-registration',
  template: '<tr>
              <td>{{objStudent.studentId}}</td>
              <td>{{objStudent.studentName}}</td>
            </tr>',
  styleUrls: ['./registration.component.css']
})
.
.
.

registration.component.ts

.
.
@Component({
  selector    : 'app-registration',
  templateURL : 'app-registration.html',
  styles      : ['
                   .present
                   {
                      background-color: greenyellow;
                   }

                   .absent
                   {
                      background-color: #fc8674;
                   }
                ']
})
.
.
.

Why we need Dependency Injection?
Its to overcome monotony behavior. If you are asking for Apple(from Apple.java) you would be served apple object. If you are asking for Mango(from Mango.java) you would be served mango object. Now in case, you are having Fruit and now you are asking Fruit(from Fruit.java) you would be served either apple or mango. Lets take a simple example as below

  1. I have a banking application where I have Account Interface with calculateIntereest Method
  2. I have different account types like SavingsAccount, PersonalLoanAccount and vehicleLoanAccount, HousingLoanAccount
  3. I have a Customer class where he would own a particular account type which wont be known until runtime

Accounts.java

package com.mugil.core;

public interface Accounts 
{
 public Integer calculateInterest();
}

SavingsAccount.java

package com.mugil.core;

public class SavingsAccount implements Accounts 
{
 public Integer calculateInterest() 
 {
  return 8;
 }
}

Customer.java

package com.mugil.core;

public class Customer {
 Accounts accountType;

 public Customer(Accounts paccountType) {
  this.accountType = paccountType;
 }

 public Accounts getAccountType() {
  return accountType;
 }

 public void setAccountType(Accounts accountType) {
  this.accountType = accountType;
 }
}

GetInterestFactory.java

package com.mugil.core;

public class GetInterestFactory {
 Accounts objAccount = null;

 public static void main(String[] args) {
  GetInterestFactory objGetInterest = new GetInterestFactory();
  objGetInterest.showInterestRate();
 }

 public void showInterestRate() {
  String strAccType = "Savings";

  switch (strAccType) {
   case "Savings":
    this.objAccount = new SavingsAccount();
    break;
   case "Vehicle":
    this.objAccount = new VehicleLoanAccount();
    break;
   default:
    this.objAccount = new SavingsAccount();
    break;
  }

  System.out.println("Interest Rate - " + this.objAccount.calculateInterest());
 }
}

Output

Interest Rate - 8
  1. In the above java code we decide the Account Type only when the switch case is executed
  2. Until then the account type is kept as generic value using interface

Now what spring does is the same code can be rewritten to determine the Account Type during runtime in setters and constructors as below

Dependency Injection without Spring using Java Constructor

  1. I have created a new class VehicleLoanAccount.java which has a different interest rate
  2. Now I am going to decide the account type in the Person.java in its constructor as below

VehicleLoanAccount.java

package com.mugil.core;

public class VehicleLoanAccount implements Accounts {
 public Integer calculateInterest() {
  return 11;
 }

}

Dependency Injection without Spring using Java Constructor
GetInterestConsWithoutSpring .java

package com.mugil.core;

public class GetInterestConsWithoutSpring {
 public static void main(String[] args) {
  Customer objPerson = new Customer(new SavingsAccount());
  System.out.println("Interest Rate - " + objPerson.getAccountType().calculateInterest());
 }
}

Output

Interest Rate - 11

Dependency Injection without Spring using Java Setter

  1. Now I am going to decide the account type in the GetInterest.java in its setter method
  2. I would be passing the value of the actual type inside the setter at runtime to decide the account type
  3. The Only thing which I have changed in the addition of new constructor to the Customer Class
  4. Setter method would be passed with specific account type during runtime

Customer.java

package com.mugil.core;

public class Customer {
 Accounts accountType;

 public Customer(Accounts paccountType) {
  this.accountType = paccountType;
 }

 public Customer() {}

 public Accounts getAccountType() {
  return accountType;
 }

 public void setAccountType(Accounts accountType) {
  this.accountType = accountType;
 }
}

Dependency Injection without Spring using Setter Method
GetInterestSettWithoutSpring .java

package com.mugil.core;

public class GetInterestSettWithoutSpring {
 public static void main(String[] args) {
  Customer customer = new Customer();
  customer.setAccountType(new SavingsAccount());
  System.out.println("Interest Rate - " + customer.getAccountType().calculateInterest());
 }
}

Output

Interest Rate - 8

Ways of Bean Injection using Spring
In Spring we can let the container create the bean in two ways

  1. Bean definition in XML
  2. Bean definition using @Component
  3. Bean definition using Java

Bean definition in XML
beans.xml

<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-2.5.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-2.5.xsd">
	<bean id="customer" class="com.mugil.core.Customer" autowire="constructor">				
	</bean>
	<bean  id="savingsType" class="com.mugil.core.SavingsAccount"/>
	<bean  id="vehicleLoanAccount" class="com.mugil.core.VehicleLoanAccount"/>		
</beans>

context:component-scan used for detecting bean
Bean definition using @Component
beans.xml

<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-2.5.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-2.5.xsd">
	<context:annotation-config />
	<context:component-scan base-package="com.mugil.core"></context:component-scan>			
</beans>

@Component marking bean
Customer.java

package com.mugil.core;

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

@Component
public class Customer 
{

 @Autowired
 @Qualifier("savings")
 Accounts accountType;
.
.
.
}

@Component marking bean
SavingsAccount.java

package com.mugil.core;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component
@Qualifier("savings")
public class SavingsAccount implements Accounts
{	
	public Integer calculateInterest() 
	{
		return 9;
	}
}

Bean definition using Java

Ways of Bean Injection using Spring
Now, what if we do the same thing from XML and using annotations. Spring offers 3 ways by which dependency injection could be done

  1. XML
    1. Constructor
    2. Setter
    3. Autowiring
      1. byType
      2. byName
      3. Constructor
      4. No
  2. Annotation Based
    1. byType
    2. byName
  3. Java Based

Constructor Based – Dependency Injection using XML

  1. In the below code beans are loaded when the application is deployed and the JVM starts
  2. The beans are uniquely identified using their IDS, in our case it is customer
  3. The parameter for constructor is defined inside constructor-arg in XML

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="customer" class="com.mugil.core.Customer">
      <constructor-arg>
         <bean id="savingAccount" class="com.mugil.core.SavingsAccount" />
      </constructor-arg>
   </bean>
</beans>

GetInterestConsWithSpring.xml

package com.mugil.core;

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

public class GetInterestConsWithSpring {
 public static void main(String[] args) {
  ApplicationContext context = new ClassPathXmlApplicationContext("SpringBeans.xml");

  Customer customer = (Customer) context.getBean("customer");

  System.out.println("Interest Rate - " + customer.getAccountType().calculateInterest());
 }
}

Output

Interest Rate - 8

Setter Based – Dependency Injection using XML

  1. For setter injection the only things we need to change is XML
  2. XML should be modified to take value by setter rather than constructor as before using property tag

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="customer" class="com.mugil.core.Customer">
      <property name="accountType" ref="savingAccount" />
   </bean>
   <bean id="savingAccount" class="com.mugil.core.SavingsAccount" />
</beans>

GetInterestSettWithSpring.xml

package com.mugil.core;

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

public class GetInterestSettWithSpring {
 public static void main(String[] args) {
  ApplicationContext context = new ClassPathXmlApplicationContext(
   "SpringBeans.xml");

  Customer customer = (Customer) context.getBean("customer");

  System.out.println("Interest Rate - " + customer.getAccountType().calculateInterest());
 }
}

Output

Interest Rate - 8

Autowiring byName

  1. In autoWiring byName the Name of the Instance Varable(accountType) and the ID of the bean in XML should be same
  2. If there is no bean matching the name is found it will throw NullPointerException

Customer.java

package com.mugil.core;

public class Customer {
 Accounts accountType;

 public Customer(Accounts paccountType) {
  this.accountType = paccountType;
 }

 public Customer() {}

 public Accounts getAccountType() {
  return accountType;
 }

 public void setAccountType(Accounts accountType) {
  this.accountType = accountType;
 }
}

Beans.xml

<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="customer" class="com.mugil.core.Customer" autowire="byName">				
	</bean>
	<bean id="accountType" class="com.mugil.core.SavingsAccount"/>
	<bean id="vehicleLoanAccount" class="com.mugil.core.VehicleLoanAccount"/>
</beans>

Output

Interest Rate - 9

What if Bean of Correct Name is notdefined in XML? Inour case it is account Type
Beans.xml

<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="customer" class="com.mugil.core.Customer" autowire="byName">				
	</bean>
	<bean id="savingAccount" class="com.mugil.core.SavingsAccount"/>
	<bean id="vehicleLoanAccount" class="com.mugil.core.VehicleLoanAccount"/>
</beans>

Output

Exception in thread "main" java.lang.NullPointerException
	at com.mugil.core.GetInterestConstAutoWiringXML.main(GetInterestConstAutoWiringXML.java:13)

Autowiring byType

  1. In autoWiring is byType then there should be at least one bean defined for the matching type, in our case it is Accounts
  2. If there is no bean defined of the type then it will throw null pointer exception
  3. If there is more than one matching bean of the same type is found it will throw No unique bean of type

Beans.xml

<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="customer" class="com.mugil.core.Customer" autowire="byType">				
	</bean>
	<bean id="savingsType" class="com.mugil.core.SavingsAccount"/>
</beans>

Output

Interest Rate - 9

What if No bean of right Type is defined in XML or More than one bean of same type defined?
Beans.xml
No bean of right Type is defined in XML

<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="customer" class="com.mugil.core.Customer" autowire="byType">				
	</bean>
</beans>

Output

Exception in thread "main" java.lang.NullPointerException
	at com.mugil.core.GetInterestConstAutoWiringXML.main(GetInterestConstAutoWiringXML.java:13)

Beans.xml
More than one bean of same type defined

<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="customer" class="com.mugil.core.Customer" autowire="byType">				
	</bean>
	<bean id="savingsType" class="com.mugil.core.SavingsAccount"/>
	<bean id="vehicleLoanAccount" class="com.mugil.core.VehicleLoanAccount"/>
</beans>

Output

Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customer' defined in class path resource [SpringBeans.xml]: Unsatisfied dependency expressed through bean property 'accountType': : No unique bean of type [com.mugil.core.Accounts] is defined: expected single matching bean but found 2: [accountType, vehicleLoanAccount]; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.mugil.core.Accounts] is defined: expected single matching bean but found 2: [accountType, vehicleLoanAccount]

Autowiring Contructor

  1. In autoWiring using Constructor spring tries to find bean using type.In our case it is Account type
  2. If there is no bean defined of the type then spring will not guess and it will throw null pointer exception
  3. If there is more than one matching bean then spring will not guess and it will throw null pointer exception
  4. If there is more than one constructor spring wont guess the bean and it will throw null pointer exception

Beans.xml

<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="customer" class="com.mugil.core.Customer" autowire="constructor">				
	</bean>
	<bean id="savingsType" class="com.mugil.core.SavingsAccount"/>
</beans>

Output

Interest Rate - 9

Beans.xml
Two bean of same type in constructor injection

<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="customer" class="com.mugil.core.Customer" autowire="constructor">				
	</bean>
	<bean id="savingsType" class="com.mugil.core.SavingsAccount"/>
<bean id="vehicleLoanAccount" class="com.mugil.core.VehicleLoanAccount"/>
</beans>

Beans.xml
No bean of matching type in constructor injection

<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="customer" class="com.mugil.core.Customer" autowire="constructor">				
	</bean>
</beans>

Output

Exception in thread "main" java.lang.NullPointerException
	at com.mugil.core.GetInterestConstAutoWiringXML.main(GetInterestConstAutoWiringXML.java:13)

Autowiring using autodetect
When the bean is configured to autowire by autodetect spring will attempt to autowire by constructor first.If no suitable constructor to bean is found then spring will attempt to autowire byType.
Beans.xml

<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="customer" class="com.mugil.core.Customer" autowire="autodetect">				
	</bean>
</beans>

Annotation Based – byType

  1. In Annotation based autowiring the beans would be injected by xml and would be available in container
  2. context:annotation-config is used to activate annotations in beans already registered in the application context (no matter if they were defined with XML or by package scanning)
  3. Now by using @Autowired tag we inject the bean as dependency where it is required.It is used either over variable in class or over setter or over constructor
  4. The default @Autowired decides the bean based on its type.If more than one bean if found it will throw no unique bean found exception.If no bean found it will throw nullpointer exception
  5. Incase of more than one bean of same type, we can narrow down the selection by using @Qualifier annotation and converting to byName @Autowiring

Beans.xml

<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-2.5.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-2.5.xsd">

	<context:annotation-config />
	<bean id="customer" class="com.mugil.core.Customer" autowire="constructor">				
	</bean>
	<bean id="savingsType" class="com.mugil.core.SavingsAccount"/>	
</beans>

Customer.java

package com.mugil.core;

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

public class Customer 
{
 @Autowired
 private Accounts accountType;

 public Customer(Accounts paccountType) {
  this.accountType = paccountType;
 }

 public Customer() {}

 public Accounts getAccountType() {
  return accountType;
 }
 
 public void setAccountType(Accounts accountType) {
  this.accountType = accountType;
 }
}

Annotation Based – byName

  1. In the below code we have two bean of same type
  2. Using @autowired would try to find bean byType.Since there are two beans it would throw no unique bean found exception
  3. Now we need to use @Qualifier passing the name (or) id of the bean as parameter
  4. Incase only Id of bean is there then same would be taken for name, If Name is there then name of bean would be given preference, incase no bean matches name then Id would be given preference

Beans.xml

<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-2.5.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-2.5.xsd">

	<context:annotation-config />
	<bean id="customer" class="com.mugil.core.Customer" autowire="constructor">				
	</bean>
	<bean name="savings" id="savingsType" class="com.mugil.core.SavingsAccount"/>
	<bean name="vehicle" id="vehicleLoanAccount" class="com.mugil.core.VehicleLoanAccount"/>		
</beans>

Customer.java

package com.mugil.core;

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

public class Customer 
{

 @Autowired
 @Qualifier("savings")
 Accounts accountType;
.
.
.
}

The below code will work by taking bean id into consideration despite the name doesn’t match.
Customer.java

package com.mugil.core;

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

public class Customer 
{

 @Autowired
 @Qualifier("savingsType")
 Accounts accountType;
.
.
.
}

What if there are two bean with the Same Name?
It will not throw exception during compilation but during runtime it will throw bean name already in use exception
Output

Exception in thread "main" org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Bean name 'savings' is already used in this file
Offending resource: class path resource [SpringBeans.xml]

What if there are two bean with the Same ID?

  1. Eclipse will complain for violating ID should be unique and you are violating
  2. If you build the code still builds but when you run will endup with Caused by: org.xml.sax.SAXParseException; lineNumber: 13; columnNumber: 69; cvc-id.2: There are multiple occurrences of ID value ‘savingsType’

Beans.xml

<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-2.5.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-2.5.xsd">

	<context:annotation-config />
	<bean id="customer" class="com.mugil.core.Customer" autowire="constructor">				
	</bean>
	<bean id="savingsType" class="com.mugil.core.SavingsAccount"/>
	<bean id="savingsType" class="com.mugil.core.VehicleLoanAccount"/>		
</beans>

Using @Component Scan to detect and load beans

  1. We can make spring to detect beans on its own by using @component annotation rather then defining in XML with bean tags
  2. Using context:component-scan with base package pointed to beans package will load the bean marked with @component annotation
  3. If there is bean of one type then it would work fine during autowiring, if there is more than one bean of same type then we should uniquely identify the bean using @qualifier annotation
  4. @qualifier annotation should be used both in the place where the bean is referred and also in the place where it is defined.In our case it is Customer.java and SavingsAccount.java

Beans.xml

<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-2.5.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-2.5.xsd">
	<context:annotation-config />
        <context:component-scan base-package="com.mugil.core"></context:component-scan>	
</beans>

Customer.java

package com.mugil.core;

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

@Component
public class Customer 
{

 @Autowired
 @Qualifier("savings")
 Accounts accountType;
.
.
.
}

SavingsAccount.java

package com.mugil.core;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component
@Qualifier("savings")
public class SavingsAccount implements Accounts
{	
	public Integer calculateInterest() 
	{
		return 9;
	}
}

What is the difference between applicationcontext and webapplicationcontext in Spring?

  1. The WebApplicationContext is an extension of the plain ApplicationContext that has some extra features necessary for web applications. It differs from a normal ApplicationContext in that it is capable of resolving themes (see Using themes), and that it knows which Servlet it is associated with (by having a link to the ServletContext). The WebApplicationContext is bound in the ServletContext, and by using static methods on the RequestContextUtils class you can always look up the WebApplicationContext if you need access to it.
  2. ApplicationContext (Root Application Context) : Every Spring MVC web application has an applicationContext.xml file which is configured as the root of context configuration. Spring loads this file and creates an applicationContext for the entire application. This file is loaded by the ContextLoaderListener which is configured as a context param in web.xml file. And there will be only one applicationContext per web application.

    WebApplicationContext : WebApplicationContext is a web aware application context i.e. it has servlet context information. A single web application can have multiple WebApplicationContext and each Dispatcher servlet (which is the front controller of Spring MVC architecture) is associated with a WebApplicationContext. The webApplicationContext configuration file *-servlet.xml is specific to a DispatcherServlet. And since a web application can have more than one dispatcher servlet configured to serve multiple requests, there can be more than one webApplicationContext file per web application.

  3. Spring allows you to build multilevel application context hierarchies, so the required bean will be fetched from the parent context if it’s not present in the current application context. In web apps as default there are two hierarchy levels, root and servlet
  4. Web Application context extended Application Context which is designed to work with the standard javax.servlet.ServletContext so it’s able to communicate with the container.
    public interface WebApplicationContext extends ApplicationContext {
        ServletContext getServletContext();
    }
    
  5. Beans, instantiated in WebApplicationContext will also be able to use ServletContext if they implement ServletContextAware interface
    package org.springframework.web.context;
    public interface ServletContextAware extends Aware 
    { 
         void setServletContext(ServletContext servletContext);
    }
    

How to define RootApplicationContext?
This two level separation comes out of the box when you use the spring servlet classes: to configure the root application context you should use context-param tag in your web.xml

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/root-context.xml
            /WEB-INF/applicationContext-security.xml
    </param-value>
</context-param>

The rootapplicationcontext is created by ContextLoaderListener which is declared in web.xml and servletApplicationContexts using servlet tag as below

<!-- rootapplicationcontext-->
<listener>
   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> 

<!-- servletApplicationContext-->
<servlet>
   <servlet-name>myservlet</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
   <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>app-servlet.xml</param-value>
   </init-param>
</servlet>

1.Why we are unable to add primitives as generic type
Allowed

 List<Integer> arrAges = new ArrayList<Integer>();

Not allowed

 List<int> arrAges = new ArrayList<int>();

This is to maintain backwards compatibility with previous JVM runtimes in the sense it could be referred by parent class instance Object. Generics in Java are encountered at compile time The compiler converts from generic type to right type as shown in the example below

List<ClassA> list = new ArrayList<ClassA>();
list.add(new ClassA());
ClassA a = list.get(0);

will be turned in to

List list = new ArrayList();
list.Add(new ClassA());
ClassA a = (ClassA)list.get(0);

So anything that is used as generics has to be convert able to Object (in this example get(0) returns an Object), and the primitive types aren’t. So they can’t be used in generics.

2.How to have a Ordered Collections

  1. keep the insertion order: LinkedHashSet and CopyOnWriteArraySet (thread-safe)
  2. keep the items sorted within the set: TreeSet, EnumSet (specific to enums) and ConcurrentSkipListSet (thread-safe)