A Bean in Spring

In Spring, the objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and managed by a Spring IoC container.

A class will only be managed by Spring container if it is declared as a spring bean using different annotations like @Component, @Repository etc, without it Spring container wont be able inject the class as a dependency into another class as spring is not aware of such classes not defined as spring bean.

Note: If you want to actually understand Spring best way is to atleast once debug its internal package and see how spring loads all the classes , it extensively uses java reflection api.

Advertisement

Dependency Injection

It is a process whereby objects define their dependencies (that is, the other objects they work with) only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method. The container then injects those dependencies when it creates the bean. 

So in simple terms before this we used to define any class in our methods like

class Example{

public void someMethod(){

DependentClass dependent=new DependentClass();

}

In DI above is not done instead through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method.

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.

@Component

@Profile(“dev”)

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:

spring_profiles_active=dev

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

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?