@Bean and @Configuration in Spring.

The @Bean annotation is used to indicate that a method instantiates, configures, and initializes a new object to be managed by the Spring IoC container. @Bean is most often used with @Configuration beans. Annotating a class with @Configuration indicates that its primary purpose is as a source of bean definitions.

While a name() attribute is available, the default strategy for determining the name of a bean is to use the name of the @Bean method.

@Bean was created to avoid coupling Spring and your business rules in compile time. It means you can reuse your business rules in other frameworks like PlayFramework or JEE.

@Configuration is meta-annotated with @Component, therefore @Configuration classes are candidates for component scanning and therefore may also take advantage of @Autowired/@Inject like any regular @Component.

Singleton design pattern in java

The singleton pattern is a design pattern that restricts the instantiation of a class to one object. Using following techniques we can make instantiation singleton.

1)Lazy initialization:

// Classical Java implementation of singleton

// design pattern

classSingleton

{

    privatestaticSingleton obj;

    // private constructor to force use of

    // getInstance() to create Singleton object

    privateSingleton() {}

    publicstaticSingleton getInstance()

    {

        if(obj==null)

            obj = newSingleton();

        returnobj;

    }

}

Singleton obj is not created until we need it and call getInstance() method. This is called lazy instantiation. Singleton obj is not created until we need it and call getInstance() method. This is called lazy instantiation.
The main problem with above method is that it is not thread safe.

Using synchronized makes sure that only one thread at a time can execute getInstance(). 
The main disadvantage of using synchronized every time while creating the singleton object is expensive and may decrease the performance. However if performance of getInstance() is not critical for your application this method provides a clean and simple solution.

2)Eager initializartion:

// Static initializer based Java implementation of

// singleton design pattern

classSingleton

{

    privatestaticSingleton obj = newSingleton();

    privateSingleton() {}

    publicstaticSingleton getInstance()

    {

        returnobj;

    }

}

Here we have created instance of singleton in static initializer. JVM executes static initializer when the class is loaded and hence this is guaranteed to be thread safe.

3)Double-checked locking:

If you notice carefully once an object is created synchronization is no longer useful because now obj will not be null and any sequence of operations will lead to consistent results. 
So we will only acquire lock on the getInstance() once, when the obj is null. This way we only synchronize the first way through, just what we want.

classSingleton

{

    privatestaticvolatileSingleton obj  = null;

    privateSingleton() {}

    publicstaticSingleton getInstance()

    {

        if(obj == null)

        {

            // To make thread safe

            synchronized(Singleton.class)

            {

                // check again as multiple threads

                // can reach above step

                if(obj==null)

                    obj = newSingleton();

            }

        }

        returnobj;

    }

}

This method drastically reduces the overhead of calling the synchronized method every time.


Singleton scope in spring

This is by default scope in spring . Only one shared instance of a singleton bean is managed, and all requests for beans with an ID that match that bean definition result in that one specific bean instance being returned by the Spring container , in short “one bean per bean id in a container“.

Suppose, I have a bean class Family. I have defined two beans from this class in bean definition, like:

<bean id="id1" class="com.example.Family"/> 
<bean id="id7" class="com.example.Family"/>

So when ever I try to get the bean with id “id1”,the spring container will create one bean, cache it and return same bean where ever referred with id1. If I try to get it with id7, another bean will be created from Sample class, same will be cached and returned each time you referred that with id7.

This is unlikely with Singleton pattern. In Singleton pattern one object per class loader is created . However in Spring, making the scope as Singleton does not restrict the container from creating many instances from that class. It just restricts new object creation for the same ID again, returning previously created object when an object is requested for the same id.

Map with case insensitive keys in Spring utils.

Keys in the java. util. HashMap are case sensitive. It means you can have both “abc” and “ABC” as keys in the same map.

There are many way around for this issue , but in Spring Utils we already have a LinkedCaseInsensitiveMap for case insensitive keys.

      public static void main(String args[]) {
	   Map<String, Object> customized=new LinkedCaseInsensitiveMap<Object>();;
	   customized.put("HELLO1", "Hello,how do you do?");
	   
	   Map<String, Object> customized2=new HashMap<String,Object>();;
	   customized.put("HELLO1", "Hello,how do you do?");
	   
	   System.out.println("Case sensitive "+customized2.get("hello1"));
	   
	   System.out.println("Case Insensitive "+customized.get("hello1"));
   }

o/p of the above —
Case sensitive null
Case Insensitive Hello,how do you do?

Is web.xml mandatory in Spring mvc?

Web.xml, also known as deployment descriptor, is traditionally used to define servlets, their mappings, servlet filters, lifecycle listeners and more. Originally it was the only way to provide such configuration. Web. xml defines mappings between URL paths and the servlets that handle requests with those paths.

With the release of the Servlet 3.0 spec it became possible to configure your Servlet Container with no web.xml. For this there is the ServletContainerInitializer in the Servlet specification. In this class you can register filters, listeners, servlets etc. as you would traditionally do in a web.xml.

To start from the beginning it is worth looking into how servlet container starts.

  • SpringServletContainerInitializer is bootstrapped automatically by any Servlet 3.0 container.
  • SpringServletContainerInitializer looks for classes implementing WebApplicationInitializer .

So to start – SpringServletContainerInitializer has to find the right class implementing WebApplicationInitializer. There are two ways of making it happen:

  1. One is by implementing WebApplicationInitializer on its own; the interface was introduced in Spring 3.1
  2. The second is by extending AbstractAnnotationConfigDispatcherServletInitializer class which also implements WebApplicationInitializer. The class was introduced in Spring 3.2 for convenience and it is “the preferred approach for applications that use Java-based Spring configuration.” . It registers a ContextLoaderlistener (optionally) and a DispatcherServlet and allows you to easily add configuration classes to load for both classes and to apply filters to the DispatcherServlet and to provide the servlet mapping.

For bootstrapping the application:

public class CustomWebApplicationInitializer
    extends AbstractAnnotationConfigDispatcherServletInitializer
{

    protected Class<?>[] getRootConfigClasses() {
        return new Class[] {RootConfig.class};
    }
    
    protected Class<?>[] getServletConfigClasses()  {
        return new Class[] {WebConfiguration .class};
    }
    
    protected String[] getServletMappings() {
        return new String[] {"/"};
    }

}

The WebMvcConfigurerAdapter is for configuring Spring MVC, the replacement of the xml file loaded by the DispatcherServlet for configuring Spring MVC. The WebMvcConfigurerAdapter should be used for a @Configuration class.

For the configuration.

@Configuration
@EnableCaching
@EnableWebMvc
@ComponentScan("")
public class WebConfiguration extends WebMvcConfigurerAdapter { ... }

This file is used in place of dispatcher servlet file. Annotating a class with the @Configuration indicates that the class can be used by the Spring IoC container as a source of bean definitions. To enable autodetection of the annotated controllers, it is required to add component scanning to the configuration. It also gives the path of base package () wherein controller files need to be searched. This class should extend WebMvcConfigurerAdapter class to serve the purpose of dispatcher servlet.

I would also like to higlight that WebMvcConfigurerAdapter should not be confused with WebApplicationInitializer. As its name suggests – it has to do with configuring “Mvc”. It is an adapter class that implements empty methods from WebMvcConfigurer. You use it when you configure your Mvc controller with @EnableWebMvc annotation.

Java OOPs- Inheritance

Inheritance in java is one of the most important concept that is used most extensively in real world applications.

In real world, a web application is made of different layers like front end, seen by user and on which user interacts ,when user sends requests to server, front layer , the one that handles the request and send requests to next layer, business layer, layer which handles all the business logic and dao layer, database layer, all these come into picture.

Every layer has a base class like for example in case of using Spring framework for mvc mechanism , we define a BaseController class , this class has all the basic methods like getting details of logged in user and storing the info in session and many more methods that can be inherited and used by all the other controller classes. A need for inheritance arises when we need some base class having all the generalized methods and fields which a specialized child class can inherit from base class and then add some more specialized methods and fields.

Inheritance in java means, by extending a class , the child class , the one that extends , inherits all the fields and methods of the parent class. Inheritance thus promotes code reusability.

Apart from classes , interfaces can also inherit from their parent interfaces by extending the same.

Lets dive deeper into inheritance

Inheritance with classes

1)In Java, when an “Is-A” relationship exists between two classes we use Inheritance.
2)The parent class is termed super class or base class and the inherited class is the sub class.
3)The keyword “extend” is used by the sub class to inherit the features of super class.

Java only supports single inheritance between classes. This means a class can inherit only from a single class , it cannot extend multiple classes.

A derived class inherits all the public and protected members from the base class, which are not static.In addition, the members with default access are inherited if the child class is in the same package as parent class.

Inheritance and Type Casting

A parent class reference can always refer to and have instance of sub class.
For example, suppose student class extends Parent class.This is referred to as upcasting (from a subclass type to a superclass type).

Student student=new Student();
Person person=student;

The above kind of instances one can find throughout java code as this is also one of the best coding practices . As long as it is possible one should declare variable type as that of Parent class, method arguments should also be declared as parent class variable to make it resuable for different child class.

Example, public void test(List list) , now this list can have instance of either an ArrayList, LinkedList any child class.

It may also be possible to cast an object from a superclass type to a subclass type, but only if the object really is an instance of that subclass (or an instance of a subclass of that subclass). This is referred to as downcasting (from a superclass type to a subclass type).

Student student=new Student();
Person person=student;
Strudent student2=(Student)person;

 

Java OOPs- Encapsulation

We can create a fully encapsulated class in java by making all the data members i.e attributes of the class private and provide getters and setters to modify or view the same.

public class Student {

private int studentId;

private String name;

private String gender;

private int age;

private String department;

public int getStudentId() {
return studentId;
}

public void setStudentId(int studentId) {
this.studentId = studentId;
}

public String getName() {
return name;
}

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

public String getGender() {
return gender;
}

public void setGender(String gender) {
this.gender = gender;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getDepartment() {
return department;
}

public void setDepartment(String department) {
this.department = department;
}

}

By declaring the member variables as private , a class can have total control over what is being stored in its fields. Other classes can only access the data members of above class through their getters and setters, the former dont have the right to manipulate the data members.

Consider, a public field in a class which can be directly accessed or modified by other classes. Now suppose later on, you want to add any extra logic while getting and setting the variable. This will impact all the other classes that uses the above declared class. So any changes to this public field will require change to each class that refers it. On the contrary, with an accessor or setter method, one can easily add some logic like cache some data(There are times when you dont want to hit the database again and again to get some data and you just add @cache to the getter method so that the data is cached and your hits to database are saved) manipulate the value passed and then return or set the member value without impacting other classes using the members.

JDK vs JRE

Today one of my juniors had this doubt whether she should install JRE or JDK on her system so I thought to share the difference on the same.

JRE: Java Runtime Environment , as the name suggests it provides required environment with its java libraries and java virtual machine(JVM) to run java programs. If you only need to run java programs then JRE is the only thing that you need on your system.

However, with JRE you can only run compiled java programs, it cannot compile java programs as it doesnt contain java compiler i.e javac to do the same. If you look into the bin folder of a JRE you wont find any javac.

JDK: Java Development Kit, it is a development kit that contains complete JRE alongwith other java development tools like java compiler i.e javac , a documentation generator i.e javadoc , java debugger. Using JDK, you compile .java files to .class files that contain bytecodes understandable by the JVM.

Internal working of HashMap in java

Basically HashMap is an array of Entry class, a static inner class defined in HashMap is as below:

static class Entry implements Map.Entry {
final K key;
V value;
Entry next;
final int hash;

//getters and setters

}

Each element in a Hashmap stores in it a key, its value, reference to next entry in case hashvalue is same for two entries in that case a linked list will be formed.

Default initial capacity of a HashMap is 16 i.e a HashMap is initialized with a default 16 sized array.

Now, lets see what happens when we put an element into HashMap.
Following is the code for put method in hashmap:

public V put(K key, V value) {
if (key == null)
return putForNullKey(value);
int hash = hash(key.hashCode());
int i = indexFor(hash, table.length);
for (Entry e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}

modCount++;
addEntry(hash, key, value, i);
return null;
}

private V putForNullKey(V value) {
for (Entry e = table[0]; e != null; e = e.next) {
if (e.key == null) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(0, null, value, 0);
return null;
}

Lets decode the above lines of code;
1)As the HashMap allows values to be stored with null keys in the map, firstly we check if key is null or not.
2)If key is null,putForNullKey method is called and null key value is placed at 0th position of array.
for (Entry e = table[0]; e != null; e = e.next) {//As each element with same hashvalue forms linked list in a hashmap array, we iterate the element using a for loop.If e==null, we add the new element.

3)If key is not null, we need to find the index in the array where we will store our element and this is done using hashing.
int hash = hash(key.hashCode());//We calculate a unique hash corresponding to each element.

int i = indexFor(hash, table.length);//Passing the hash and array length we find the position in array to store the element.

static int indexFor(int h, int length) {
return h & (length-1);
}

As you can see we do & operation between array length and hash value and thus a location is found from 1to16, so suppose hash value is 00000000 00010000 & 00000000 00010000, will give an index of 16.

4)Next we check if an element entry exists at above found index if it doesnt exist we add the new element entry but if an entry element already exists at the index position , here comes the linkedlist into the picture.

5)In the if condition if (e.hash == hash && ((k = e.key) == key || key.equals(k))) , we compare the hash value and a comparison with the equals method written for the object or for the same references.

6)If above condition is true, old value is replaced with new value.
7)If 5th condition is false, we iterate the linked list till we find the exact key location and put the entry element.

Implementing two interfaces with same default methods.

In java8 , a new concept is introduced wherein we can provide implementation for methods in an interface using default keyword. But what will happen if a class implements two interfaces with same default methods , which method the implementing class will inherit. Let us see this in the following working example.

I have one interface, TestInterface1 with a default method test()

package com.test;

public interface TestInterface1 {

public default void test() {
System.out.println(“hi”);
}
}

An another interface, TestInterface2 too has implementation for method test()

package com.test;

public interface TestInterface2 {

default public void test() {
System.out.println(“hello”);
}
}

Now, if I have a class Test that implements above two interfaces , the compiler gives me an error “Duplicate default methods named test with the parameters () and () are inherited from the types TestInterface2 and TestInterface1”

package com.test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static java.util.stream.Collectors.*;

import java.lang.reflect.Method;

public class Test implements TestInterface1,TestInterface2{

public static void main(String[] args) {
Test test=new Test();
test.test();

}

However, I can remove the above error by providing the compiler which interface method implementation I need in my implementation class.

package com.test;

public class Test implements TestInterface1,TestInterface2{

public static void main(String[] args) {
Test test=new Test();
test.test();

}

@Override
public void test() {
// TODO Auto-generated method stub
TestInterface1.super.test(); }
}

So, as shown above in my implementation class method I need to call the method with the interface name whose method implementation I need.