@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- 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.

Deep vs Shallow Copy

package com.test;
public class User implements Cloneable{
private String name;
private Integer age;
private Address address;

public User(String name, Integer age, Address address) {
super();
this.name = name;
this.age = age;
this.address = address;
}
@Override
public Object clone() throws CloneNotSupportedException{
return super.clone();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public static void main(String[] args) {
Address add=new Address(“243″,”Ghaziabad road”,”Gujarat”);
User user=new User(“sunita”,50,add);
User userClone=null;
try {
userClone=(User)user.clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(“Original user address–“+user.getAddress());
System.out.println(“Cloned user address–“+userClone.getAddress());

}
}

Output for above sysouts:
Original user address–com.test.Address@15db9742
Cloned user address–com.test.Address@15db9742

As you can see above in a shallow copy, userclone creates a copy of name and age primitive attributes, however for address it reuses the same address object for userclone. So, now the clone object has a copy of primitive values but the object references refer to the same objects as the original copy.

Shallow Copies have a significant drawback. As we saw above, cloned object and original copy refer to the same address object. Any change that cloned object makes in address object will also be reflected in original copy, which is an unwanted behaviour. What we really wanted is two separate copies of user object. Deep copying comes to our rescue for this kind of situation.

Deep copying not just clones the primitive values, it also creates copies of object references.

user and userClone have their own instances of empAddress. Any change done to user’s address will not have any affect on userClone’s address and vice-a-versa.

To implement deep copying – User will still need to implement Cloneable, and it will still override Object.clone() method. But inside the overridden clone() method, instead of calling super.clone(), a clone of an User object is constructed step-by-step using custom code as shown in the code below –

@Override
public Object clone() throws CloneNotSupportedException {
User userClone = (User) super.clone();
Address addressClone = new Address(this.address.getHouseNo(),
this.address.getStreet(),
this.address.getCity());
userClone.address(addressClone);
return userClone;
}

String,String constant pool in java

String grima = “grima”;
String gri = “grima”;
if (grima == gri)
System.out.println(“grima == gri”); // The message is displayed

Both grima,grima references refer to same “grima” in string constant pool.

String pndey = “pandey”;
String pan = “pande”;
pan = pan + “y”; // The value for pan will be resolved during runtime.
if (pndey == pan)
System.out.println(“pndey == pan”); // The 2 references are different

Now in the second case if i change

pan = pan + “y”;this line to –>pan=”pande” +”y”, System.out.println(“pndey == pan”); message will be displayed because the compiler resolves the literal during compilation time itself.

Now as per java docs on string:

•Literal strings within the same class (§8 (Classes)) in the same package (§7 (Packages)) represent references to the same String object (§4.3.1).

•Literal strings within different classes in the same package represent references to the same String object.

•Literal strings within different classes in different packages likewise represent references to the same String object.

•Strings computed by constant expressions (§15.28) are computed at compile time and then treated as if they were literals.

•Strings computed by concatenation at run time are newly created and therefore distinct.

•The result of explicitly interning a computed string is the same string as any pre-existing literal string with the same contents.