Spring Profiles

We use the @Profile annotation — When we have beans specific to a particular profile; the annotation simply takes the names of one (or multiple) profiles.



public class RootConfig

The next step is to activate and set the profiles so that the respective beans are registered in the container.

profiles can be activated via the environment variable:


Enable hikaricp logs in spring boot

Add logging.level.com.zaxxer.hikari: DEBUG property to application.yml.

* Log the current pool state at debug level.
* @param prefix an optional prefix to prepend the log message
void logPoolState(String… prefix)
if (logger.isDebugEnabled()) {
logger.debug(“{} – {}stats (total={}, active={}, idle={}, waiting={})”,
poolName, (prefix.length > 0 ? prefix[0] : “”),
getTotalConnections(), getActiveConnections(), getIdleConnections(), getThreadsAwaitingConnection());

Above method called in HikariPool.java prints the info time to time from HouseKeeper class.

Surprise!!!! Integer.getInteger is not to retrieve any Integer value from a String.

I recently learned this that actually

 public static Integer getInteger(String nm) {
        return getInteger(nm, null);

method in Integer class doesnt return Integer value from a string, for example

Integer.getInteger(“123”) will not return 123 but instead null .

This is because if we take a look in the internal code for above method

public static Integer getInteger(String nm, Integer val) {
    String v = null;
    try {
        v = System.getProperty(nm);
    } catch (IllegalArgumentException | NullPointerException e) {
    if (v != null) {
        try {
            return Integer.decode(v);
        } catch (NumberFormatException e) {
    return val;

The getInteger returns the integer value of the system property with the specified name.

So for “123”,

v = System.getProperty(nm); will look for some system property with name as 123 and in its absence will return null.

System properties are accessible through the method. The
System.getProperty(nm) . String value of this property is then interpreted as an integer value using Integer.decode(v) and Integer object representing this value is returned.

@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



    privatestaticSingleton obj;

    // private constructor to force use of

    // getInstance() to create Singleton object

    privateSingleton() {}

    publicstaticSingleton getInstance()



            obj = newSingleton();




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



    privatestaticSingleton obj = newSingleton();

    privateSingleton() {}

    publicstaticSingleton getInstance()





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.



    privatestaticvolatileSingleton obj  = null;

    privateSingleton() {}

    publicstaticSingleton getInstance()


        if(obj == null)


            // To make thread safe



                // check again as multiple threads

                // can reach above step


                    obj = newSingleton();






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.

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.