What is Dispatcher Servlet ?

DispatcherServlet is the class which manages the entire request handling process. Like a normal servlet DispatcherServlet also needs to be configured in the web deployment Descriptor(web.xml).By default, DispatcherServlet will look for a name dispatcher-servlet.xml to load the Spring MVC configuration.

<servlet>
  <servlet-name>dispatcher</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>dispatcher</servlet-name>
  <url-pattern>/</url-pattern>
</servlet-mapping>

For more detail, Please watch below video –

 

 

 

What is init param & contextconfigLocation ?

Servlet Init Parameters. A servlets init() method is called when the servlet container loads the servlet for the first time.

If we want to change the name of the dispatcher-servlet file name or change its location, we can add init-param with contextConfigLocation as param-name, as can be seen below

<init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>WEB-INF/spring-servlet.xml</param-value>
</init-param>

For more detail, Please watch below video –

 

 

 

Thanks for reading 🙂

Please Subscribe our you tube channel Almighty Java

What is Autowire in Spring ?

The Spring container can autowire relationships between collaborating beans without using <constructor-arg> and <property> elements which helps cut down on the amount of XML configuration you write for a big Spring-based application.

Autowiring Modes

  • no – It is the default autowiring mode. It means no autowiring by default.
  • byname – The byName mode injects the object dependency according to the name of the bean. In such case, property name and bean name must be same. It internally calls setter method.
  • byTypeThe byType mode injects the object dependency according to type. So property name and bean name can be different. It internally calls setter method.
  • Constructor – The constructor mode injects the dependency by calling the constructor of the class. It calls the constructor having a large number of parameters.
  • autodetectIt is deprecated since Spring 3

Autowire using Annotation

  • To enable annotation need to add <context:annotation-config /> in XML file.
  • The @Autowired annotation provides more fine-grained control over where and how autowiring should be accomplished. The @Autowired annotation can be used to autowire bean on the setter method just like @Required annotation, constructor, a property or methods with arbitrary names and/or multiple arguments.
  • There may be a situation when you create more than one bean of the same type and want to wire only one of them with a property, in such case you can use @Qualifier annotation along with @Autowired to remove the confusion by specifying which exact bean will be wired.

Let’s Implement – using bean

Project structure be like below image

9

add a dependency on pom.xml file –

<dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-context</artifactId>
     <version>4.3.4.RELEASE</version>
</dependency>

bean class “Greetings.java

package com.spring.core;
public class Greetings {
    private Greetings2 greetings2;   
    /*public Greetings(Greetings2 greetings2) {
        this.greetings2 = greetings2;
    }*/
    public Greetings2 getGreetings2() {
        return greetings2;
    }
    public void setGreetings2(Greetings2 greetings2) {
        this.greetings2 = greetings2;
    }
}

bean class “Greetings2.java

package com.spring.core;
public class Greetings2 {
    private String message;   
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}

beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
        "http://www.springframework.org/dtd/spring-beans-2.0.dtd">        
<beans>
    <bean id="greetings" class="com.spring.core.Greetings" autowire="byName"></bean>    
    <!-- <bean id="greetings" class="com.spring.core.Greetings" autowire="byType"></bean> -->    
    <!-- <bean id="greetings" class="com.spring.core.Greetings" autowire="autodetect"></bean> -->
    <!-- <bean id="greetings" class="com.spring.core.Greetings" autowire="constructor"></bean> -->
    <bean id="greetings2" class="com.spring.core.Greetings2">
        <property name="message" value="Hello Spring"></property>
    </bean>  
</beans>

Application Main class

package com.spring.core;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Application {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Greetings greetings = (Greetings) context.getBean("greetings"); 
        System.out.println(greetings.getGreetings2()+" : "+greetings.getGreetings2().getMessage());
    }
}

Output –

Dec 28, 2016 1:37:07 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@300ffa5d: startup date [Wed Dec 28 13:37:07 IST 2016]; root of context hierarchy
Dec 28, 2016 1:37:07 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [beans.xml]
com.spring.core.Greetings2@1ce92674 : Hello Spring

Lets Implement @Autowired using Annotation

Project structure be like above image, Greetings2.java like the above

beans.xml need to enable annotation-driven

<?xml version="1.0" encoding="UTF-8"?>
<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-3.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
    <context:annotation-config />    
    <bean id="greetings" class="com.spring.core.Greetings"></bean>    
    <bean id="greetings2" class="com.spring.core.Greetings2">
        <property name="message" value="Hello Spring"></property>
    </bean>    
    <!-- in this scenario we will use qualifier -->
    <!-- <bean id="greetings3" class="com.spring.core.Greetings2">
        <property name="message" value="Hello Spring 2"></property>
    </bean> -->
</beans>

bean class “Greetings.java

package com.spring.core;
import org.springframework.beans.factory.annotation.Autowired;
public class Greetings {   
    @Autowired
    //@Qualifier("greetings3")
    private Greetings2 greetings2;    
    public Greetings2 getGreetings2() {
        return greetings2;
    }
    public void setGreetings2(Greetings2 greetings2) {
        this.greetings2 = greetings2;
    }    
}

Application main class

package com.spring.core;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Application {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Greetings greetings = (Greetings) context.getBean("greetings"); 
        System.out.println(greetings+" : "+greetings.getGreetings2()+" : "+greetings.getGreetings2().getMessage());
    }
}

Output –

Dec 28, 2016 1:41:54 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@300ffa5d: startup date [Wed Dec 28 13:41:54 IST 2016]; root of context hierarchy
Dec 28, 2016 1:41:54 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [beans.xml]
com.spring.core.Greetings@543c6f6d : com.spring.core.Greetings2@13eb8acf : Hello Spring

For more detail, Please watch below video –

Thanks for reading 🙂

Please Subscribe our you tube channel Almighty Java

How to create bean using Annotation in Spring ?

@Configuration – Annotating a class with the @Configuration annotation indicates that the class will be used by Java Config as a source of bean definitions. An application may make use of just one @Configuration-annotated class or many. @Configuration can be considered the equivalent of XML’s element. Like, it provides an opportunity to explicitly set defaults for all enclosed bean definitions.

@Bean – It is a method-level annotation and a direct analog of the XML element. The annotation supports most of the attributes offered by such as init-method, destroy-method, auto wiring, lazy-init, dependency-check, depends-on and scope.

How to declare a bean using annotation?

<beans>
     <bean name=“service” class=”com.spring.core.ServiceImpl”/>
</beans>

Is equal to

@Configuration
public class AppConfig {
     @Bean
     public Service service() {
          return new ServiceImpl();
     }
}

Lets Implement Simple One

Project structure be like below image

6.png

add the dependency in pom.xml file –

<dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-context</artifactId>
     <version>4.3.4.RELEASE</version>
</dependency>

bean class “Greetings.java

package com.spring.core;
public class Greetings {
    private String message;
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}

In beans.xml need to enable annotation-driven

<?xml version="1.0" encoding="UTF-8"?>
<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-3.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
    <context:annotation-config />
</beans

BeanConfig – annotation is enabled so can use @Configuration, @Bean, and @Scope

package com.spring.core;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
@Configuration
public class BeanConfig {
    @Bean
    @Scope(value="prototype")
    public Greetings createGreetings() {
        Greetings greetings = new Greetings();
        greetings.setMessage("Hello Spring");
        return greetings;
    }
}

Application Main class

package com.spring.core;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
public class Application {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(BeanConfig.class);
        Greetings greet = (Greetings) context.getBean(Greetings.class);
        System.out.println(greet+" : "+greet.getMessage());     
        Greetings greet2 = (Greetings) context.getBean(Greetings.class);
        System.out.println(greet2+" : "+greet2.getMessage());
    }
}

Output –

Dec 28, 2016 1:15:26 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@5e9f23b4: startup date [Wed Dec 28 13:15:26 IST 2016]; root of context hierarchy
com.spring.core.Greetings@5cdd8682 : Hello Spring
com.spring.core.Greetings@d6da883 : Hello Spring

Let’s Implement Multiple POJO

Project structure be like below image

7

beans.xml, BeanConfig, and Greetings like the above

bean class “Greetings2.java

package com.spring.core.pojo;
public class Greetings2 {
    private String message; 
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}

BeanConfig2

package com.spring.core.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.spring.core.pojo.Greetings2;
@Configuration
public class BeanConfig2 {
    @Bean
    public Greetings2 createGreetings2() {
        Greetings2 greetings2 = new Greetings2();
        greetings2.setMessage("Hello Spring 2");
        return greetings2;
    }
}

Application Main class – so multiple configurations is there then need to register

package com.spring.core;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import com.spring.core.config.BeanConfig;
import com.spring.core.config.BeanConfig2;
import com.spring.core.pojo.Greetings;
import com.spring.core.pojo.Greetings2;
public class Application {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.register(BeanConfig.class, BeanConfig2.class);     
        context.refresh();        
        Greetings greet = (Greetings) context.getBean(Greetings.class);
        System.out.println(greet+" : "+greet.getMessage());        
        Greetings2 greet2 = (Greetings2) context.getBean(Greetings2.class);
        System.out.println(greet2+" : "+greet2.getMessage());
    }
}

Output –

Dec 28, 2016 1:22:57 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@5e9f23b4: startup date [Wed Dec 28 13:22:57 IST 2016]; root of context hierarchy
com.spring.core.pojo.Greetings@679b62af : Hello Spring
com.spring.core.pojo.Greetings2@5cdd8682 : Hello Spring 2

Let’s Implement when beans are dependent on others

Project structure be like below image

8

beans.xml, BeanConfig2 and Greetings, Greeting2 like the above

bean class “Greetings3.java

package com.spring.core.pojo;
public class Greetings3 {
    private Greetings greetings;
    public Greetings getGreetings() {
        return greetings;
    }
    public void setGreetings(Greetings greetings) {
        this.greetings = greetings;
    }
}

BeanConfig

package com.spring.core.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import com.spring.core.pojo.Greetings;
import com.spring.core.pojo.Greetings3;
@Configuration
public class BeanConfig {  
    @Bean
    @Scope(scopeName="prototype")
    //@Scope(value="prototype")
    public Greetings createGreetings() {
        Greetings greetings = new Greetings();
        greetings.setMessage("Hello Spring");
        return greetings;
    }    
    @Bean
    public Greetings3 createGreetings3() {
        Greetings3 greetings2 = new Greetings3();
        greetings2.setGreetings(createGreetings());
        return greetings2;
    }
}

Application Main class –

package com.spring.core;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import com.spring.core.config.BeanConfig;
import com.spring.core.config.BeanConfig2;
import com.spring.core.pojo.Greetings;
import com.spring.core.pojo.Greetings2;
import com.spring.core.pojo.Greetings3;
@Configuration
public class Application {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.register(BeanConfig.class, BeanConfig2.class);
        context.refresh();
        Greetings greet = (Greetings) context.getBean(Greetings.class);
        System.out.println(greet + " : " + greet.getMessage());
        Greetings2 greet2 = (Greetings2) context.getBean(Greetings2.class);
        System.out.println(greet2 + " : " + greet2.getMessage());
        Greetings3 greet3 = (Greetings3) context.getBean(Greetings3.class);
        System.out.println(greet3 + " : " + greet3.getGreetings() + " : " + greet3.getGreetings().getMessage());
    }
}

Output –

Dec 28, 2016 1:30:09 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@5e9f23b4: startup date [Wed Dec 28 13:30:09 IST 2016]; root of context hierarchy
com.spring.core.pojo.Greetings@69a10787 : Hello Spring
com.spring.core.pojo.Greetings2@2d127a61 : Hello Spring 2
com.spring.core.pojo.Greetings3@2bbaf4f0 : com.spring.core.pojo.Greetings@11c20519 : Hello Spring

For more detail, Please watch below video –

 

Thanks for reading 🙂

Please Subscribe our you tube channel Almighty Java

How to write custom event in Spring ?

Spring’s ApplicationContext provides the functionality to support events and listeners in code. We can create beans that listen for events which are published through our ApplicationContext. This is achieved via the ApplicationEventPublisher interface.

There are a few simple guidelines to follow:

  • The event should extend ApplicationEvent
  • The publisher should inject an ApplicationEventPublisher object
  • The listener should implement the ApplicationListener interface

Ex – Password changed event like whenever password will change email should trigger on registered mail id.

Lets Implement

Project structure be like below image

5

add a dependency on pom.xml file –

<dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-context</artifactId>
     <version>4.3.4.RELEASE</version>
</dependency>

bean class “Greetings.java

package com.spring.core;
public class Greetings {
    private String message;
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}

UserDefinedEvent

package com.spring.core.event;
import org.springframework.context.ApplicationEvent;
public class UserDefinedEvent extends ApplicationEvent {
    private static final long serialVersionUID = -4264109794317707068L;
    public UserDefinedEvent(Object source) {
        super(source);
    }
    @Override
    public String toString() {
        return "user defined event";
    }
}

UserDefinedEventHandler

package com.spring.core.event;
import org.springframework.context.ApplicationListener;
public class UserDefinedEventHandler implements ApplicationListener<UserDefinedEvent> {
    @Override
    public void onApplicationEvent(UserDefinedEvent event) {
        System.out.println(event);        
    }
}

UserDefinedEventPublisher

package com.spring.core.publisher;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import com.spring.core.event.UserDefinedEvent;
public class UserDefinedEventPublisher implements ApplicationEventPublisherAware {
    private ApplicationEventPublisher publisher;
    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
        this.publisher = publisher;
    }
    public void publish() {
        UserDefinedEvent userDefinedEvent = new UserDefinedEvent(publisher);
        publisher.publishEvent(userDefinedEvent);
    }
}

beans.xml be like

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
        "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
    <bean id="greet" class="com.spring.core.Greetings">
        <property name="message" value="Hello One"></property>
    </bean>
    <bean id="eventHandler" class="com.spring.core.event.UserDefinedEventHandler"></bean>
    <bean id="eventPublisher" class="com.spring.core.publisher.UserDefinedEventPublisher"></bean>
</beans>

Output –

Dec 28, 2016 1:06:02 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@300ffa5d: startup date [Wed Dec 28 13:06:02 IST 2016]; root of context hierarchy
Dec 28, 2016 1:06:02 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [beans.xml]
Hello One
user defined event

For more detail, Please watch below video –

Thanks for reading 🙂

Please Subscribe our you tube channel Almighty Java

What are Bean Scopes ?

In the spring bean configurations, bean attribute called ‘scope’ defines what kind of object has to created and returned

<bean id = “” class = “” scope = “”></bean>

When you create a bean definition what you are actually creating is an actual instance of the class defined by that bean definition.

So you can control object creation using scope attribute. This approach is very powerful and gives you the flexibility to choose the scope of the objects you create through configuration instead of having to the scope of an object at the Java class level.

Spring Framework supports five scopes

Scope Description
singleton Scopes a single bean definition to a single object instance per Spring IoC container.
prototype Scopes a single bean definition for any number of object instances.
request Scopes a single bean definition to the lifecycle of a single HTTP request that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
session Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
global session Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.

The singleton scope

  • Singleton scope is the default one.
  • Singleton scope should be used for stateless beans.
  • When a bean is a singleton, only one shared an instance of the bean will be managed, and all requests for beans with an id or ids matching that bean definition will result in that one specific bean instance being returned by the Spring container.
  • When you define a bean definition and it is scoped as a singleton, then the Spring IoC container will create exactly one instance of the object defined by that bean definition.
  • This single instance will be stored in a cache of such singleton beans, and all subsequent requests and references for that named bean will result in the cached object being returned.

Singleton Example

<!– by default singleton -->
<bean id=“service" class="com.foo.TestService"/>

<!– using spring-beans-2.0.dtd -->
<bean id=“service" class="com.foo.TestService" scope="singleton"/>

<!– backward compatibility in spring-beans.dtd -->
<bean id=“service" class="com.foo.TestService" singleton=“true”/>

The prototype scope

  • Prototype scope for all beans that are stateful.
  • Prototype scope of bean deployment results in the creation of a new bean instance every time a request for that specific bean is made.
  • Spring does not manage the complete lifecycle of a prototype bean: the container instantiates, configures, decorates and otherwise assembles a prototype object, hands it to the client and then has no further knowledge of that prototype instance.
  • This means that while initialization lifecycle callback methods will be called on all objects regardless of scope, in the case of prototypes, any configured destruction lifecycle callbacks will not be called.
  • It is the responsibility of the client code to clean up prototype scoped objects and release any expensive resources that the prototype bean(s) are holding onto. (One possible way to get the Spring container to release resources used by prototype-scoped beans is through the use of a custom bean post-processor which would hold a reference to the beans that need to be cleaned up.

Prototype Example

<!– using spring-beans-2.0.dtd -->
<bean id=“service" class="com.foo.TestService" scope=“prototype"/>

<!– backward compatibility in spring-beans.dtd -->
<bean id=“service" class="com.foo.TestService" singleton=“false”/>

Other Scope

The other scopes, namely request, session, and global session are for use only in web-based applications.

If you are using a web-aware Spring ApplicationContext implementation (such as XmlWebApplicationContext). If you try using these next scopes with regular Spring IoC containers such as the XmlBeanFactory or ClassPathXmlApplicationContext, you will get an IllegalStateException complaining about an unknown bean scope.

Other Scopes Examples

  • Request – Spring container will create a brand new instance of the LoginAction bean using the ‘loginAction’ bean definition for each and every HTTP request. When the request is finished processing, the bean that is scoped to the request will be discarded.
  • Session – Spring container will create a brand new instance of the UserPreferences bean using the ‘userPreferences’ bean definition for the lifetime of a single HTTP Session. When the HTTP Session is eventually discarded, the bean that is scoped to that particular HTTP Session will also be discarded.
  • Global Session – The global session scope is similar to the standard HTTP Session scope, and really only makes sense in the context of portlet-based web applications.

Spring Singleton v/s Singleton Design Pattern

  • Spring singleton is described as “per container per bean”. Or Singleton scope in spring means the single instance in a spring context.
  • Singleton pattern says that one and only one instance of a particular class will ever be created per class loader.
  • Spring singleton bean can be any normal class you write, but declaring it’s scope as singleton means that Spring will only create one instance and provide its reference to all beans that reference the declared bean. You may have many instances of that class in your application, but only one will be created for that bean. You may even have multiple beans of the same class all declared as the singleton. Each bean will create exactly one instance of the class.
  • A Java singleton, per the design pattern where instantiation is restricted to one, usually per JVM class loader by the code.

Lets Implement

Project structure be like below image

1

add the dependency in pom.xml file –

<dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-context</artifactId>
     <version>4.3.4.RELEASE</version>
</dependency>

bean class “Greetings.java

package com.spring.core;
public class Greetings {
    private String message;
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}

beans.xml configuration be like

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
        "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
    <!-- By default "Singleton" -->
    <bean id="greet1" class="com.spring.core.Greetings">  
        <property name="message" value="Hello One"></property>
    </bean>
    <bean id="greet2" class="com.spring.core.Greetings">  
        <property name="message" value="Hello One"></property>
    </bean>
    <!-- you can change to "Prototype" also -->
    <!-- <bean id="greet" class="com.spring.core.Greetings" scope="prototype">  
        <property name="message" value="Hello One"></property>
    </bean> -->
</beans>

Application main class

package com.spring.core;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Application {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Greetings greet = (Greetings) context.getBean("greet1");  
        System.out.println(greet+" : "+greet.getMessage());  
        Greetings greet1 = (Greetings) context.getBean("greet2"); 
        System.out.println(greet1+" : "+greet1.getMessage());
    }
}

Output –

Dec 28, 2016 12:59:29 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@300ffa5d: startup date [Wed Dec 28 12:59:29 IST 2016]; root of context hierarchy
Dec 28, 2016 12:59:29 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [beans.xml]
com.spring.core.Greetings@3fee9989 : Hello One
com.spring.core.Greetings@73ad2d6 : Hello One

For more detail, Please watch below video –

 

Thanks for reading 🙂

Please Subscribe our you tube channel Almighty Java

What is Application Listener in Spring ?

Application Listener can generically declare the event type that it is interested in. When registered with a Spring Application Context, events will be filtered accordingly, with the listener getting invoked for matching event objects only.

Application events are available since the very beginning of the Spring framework as a mean for loosely coupled components to exchange information.

Types of event are available –

  • Start – ContextStartedEvent
  • Stop – ContextStoppedEvent
  • Refresh – ContextRefreshedEvent
  • Close – ContextClosedEvent

Lets Implement

Project structure be like below image

4

add the dependency in pom.xml file –

<dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-context</artifactId>
     <version>4.3.4.RELEASE</version>
</dependency>

bean class “Greetings.java

package com.spring.core;
public class Greetings {
    private String message;
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}

ContextRefreshHandler

package com.spring.core;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
public class ContextRefreshHandler implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        System.out.println("Context Refresh Event Received");
    }
}

ContextStartHandler

package com.spring.core;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextStartedEvent;
public class ContextStartHandler implements ApplicationListener<ContextStartedEvent> {
    @Override
    public void onApplicationEvent(ContextStartedEvent event) {
        System.out.println("Context Start Event Received");
    }
}

ContextStopHandler

package com.spring.core;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextStoppedEvent;
public class ContextStopHandler implements ApplicationListener<ContextStoppedEvent> {
    @Override
    public void onApplicationEvent(ContextStoppedEvent event) {
        System.out.println("Context Stop Event Received");
    }
}

ContextCloseHandler

package com.spring.core;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
public class ContextCloseHandler implements ApplicationListener<ContextClosedEvent> {
    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        System.out.println("Context Close Event Received");
    }
}

beans.xml configuration be like

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
        "http://www.springframework.org/dtd/spring-beans-2.0.dtd">    
<beans>
    <bean id="greet" class="com.spring.core.Greetings">
        <property name="message" value="Hello One"></property>
    </bean>    
    <bean id="contextStart" class="com.spring.core.ContextStartHandler"></bean>
    <bean id="contextStop" class="com.spring.core.ContextStopHandler"></bean>
    
    <bean id="contextRefresh" class="com.spring.core.ContextRefreshHandler"></bean>
    <bean id="contextClose" class="com.spring.core.ContextCloseHandler"></bean>
</beans>

Application main class

package com.spring.core;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Application {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        context.start();
        Greetings greet = (Greetings) context.getBean("greet"); 
        System.out.println(greet.getMessage());
        context.refresh();
        context.stop();
        context.close();
    }
}

Output –

Dec 28, 2016 12:48:13 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@300ffa5d: startup date [Wed Dec 28 12:48:13 IST 2016]; root of context hierarchy
Dec 28, 2016 12:48:13 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [beans.xml]
Context Refresh Event Received
Context Start Event Received
Hello One
Dec 28, 2016 12:48:13 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@300ffa5d: startup date [Wed Dec 28 12:48:13 IST 2016]; root of context hierarchy
Dec 28, 2016 12:48:13 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [beans.xml]
Context Refresh Event Received
Context Stop Event Received
Dec 28, 2016 12:48:13 PM org.springframework.context.support.ClassPathXmlApplicationContext doClose
INFO: Closing org.springframework.context.support.ClassPathXmlApplicationContext@300ffa5d: startup date [Wed Dec 28 12:48:13 IST 2016]; root of context hierarchy
Context Close Event Received

For more details, watch below video –

Thanks for reading 🙂

Please Subscribe our you tube channel Almighty Java

Spring Bean Post Processors

BeanPostProcessor provides a way to perform some operations before creating a spring bean and immediately after creating spring bean. So you can add some logic before and after creating the bean.

Follow steps to implement spring bean post processors –

  • Implements BeanPostProcessor in Processor class.
  • Overrides methods provided by BeanPostProcessor and add some logic whatever you want in postProcessBeforeInitialization and postProcessAfterInitialization
  • Create bean for the class who implement BeanPostProcessor in .xml file

Lets Implement

Project structure be like below image

3

add a dependency on pom.xml file –

<dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-context</artifactId>
     <version>4.3.4.RELEASE</version>
</dependency>

bean class “Greetings.java

package com.spring.core;
public class Greetings {
    private String message;
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public void init() {
        System.out.println("Init");
    }
    public void destroy() {
        System.out.println("Destroy");
    }
}

Processor.java

package com.spring.core;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
public class Processor implements BeanPostProcessor {
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("After Process Initialization Bean - "+bean+" and Name - "+beanName);
        return bean;
    }
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("Before Process Initialization Bean - "+bean+" and Name - "+beanName);
        return bean;
    }
}

beans.xml file is in classpath

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
        "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans default-init-method="init" default-destroy-method="destroy">
    <bean id="greet" class="com.spring.core.Greetings">
        <property name="message" value="Hello One"></property>
    </bean>
    <bean id="processor" class="com.spring.core.Processor"></bean>
</beans>

Main class

package com.spring.core;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Application { 
    public static void main(String[] args) {
        AbstractApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Greetings greet = (Greetings) context.getBean("greet"); 
        System.out.println(greet.getMessage());
        context.registerShutdownHook();
    }
}

Output –

Dec 28, 2016 12:31:32 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@300ffa5d: startup date [Wed Dec 28 12:31:32 IST 2016]; root of context hierarchy
Dec 28, 2016 12:31:32 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [beans.xml]
Before Process Initialization Bean - com.spring.core.Greetings@14bf9759 and Name - greet
Init
After Process Initialization Bean - com.spring.core.Greetings@14bf9759 and Name - greet
Hello One
Dec 28, 2016 12:31:32 PM org.springframework.context.support.ClassPathXmlApplicationContext doClose
INFO: Closing org.springframework.context.support.ClassPathXmlApplicationContext@300ffa5d: startup date [Wed Dec 28 12:31:32 IST 2016]; root of context hierarchy
Destroy

For more details – watch video

Thanks for reading 🙂

Please Subscribe our you tube channel Almighty Java

Life Cycle of Bean

The life cycle of Bean is easy to understand When a bean is instantiated, it may be required to perform some initialization to get it into a usable state. Similarly, when the bean is no longer required and is removed from the container, some cleanup may be required.

you can use init-method and destroy-method as an attribute in bean configuration file for the bean to perform certain actions upon initialization and destruction.

Initialization – org.springframework.beans.factory.InitializingBean interface  contains one single method “void afterPropertiesSet() throws Exception;”

Destruction – org.springframework.beans.factory.DisposableBean interface  contains one single method “void destroy() throws Exception;”

Lets Implement

Project structure be like below image

1

add the dependency in pom.xml file –

<dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-context</artifactId>
     <version>4.3.4.RELEASE</version>
</dependency>

bean class “Greetings.java

package com.spring.core;
public class Greetings {
    private String message;
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public void init() {
        System.out.println("Init");
    }
    public void destroy() {
        System.out.println("Destroy");
    }
}

beans.xml file is in the classpath

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
        "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<!-- use any one either type 1 or type 2 -->
<!-- type 1 -->     
<beans>
    <bean id="greet" class="com.spring.core.Greetings" init-method="init" destroy-method="destroy">
        <property name="message" value="Hello One"></property>
    </bean>
</beans>

<!-- type 2 -->
<beans default-init-method="init" default-destroy-method="destroy">
    <bean id="greet" class="com.spring.core.Greetings">
        <property name="message" value="Hello One"></property>
    </bean>
</beans>

Main class

package com.spring.core;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Application { 
    public static void main(String[] args) {
        AbstractApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Greetings greet = (Greetings) context.getBean("greet"); 
        System.out.println(greet.getMessage());
        context.registerShutdownHook();
    }
}

Output –

Dec 28, 2016 12:29:18 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@300ffa5d: startup date [Wed Dec 28 12:29:18 IST 2016]; root of context hierarchy
Dec 28, 2016 12:29:18 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [beans.xml]
Init
Hello One
Dec 28, 2016 12:29:18 PM org.springframework.context.support.ClassPathXmlApplicationContext doClose
INFO: Closing org.springframework.context.support.ClassPathXmlApplicationContext@300ffa5d: startup date [Wed Dec 28 12:29:18 IST 2016]; root of context hierarchy
Destroy

For more details – watch video

Thanks for reading 🙂

Please Subscribe our you tube channel Almighty Java

Bean Factory vs Application Context

Bean Factory Hierarchy

  • public interface BeanFactory
  • public interface ListableBeanFactory extends BeanFactory
  • public interface ConfigurableListableBeanFactory extends ListableBeanFactory, AutowireCapableBeanFactory, ConfigurableBeanFactory
  • public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable
  • public class XmlBeanFactory extends DefaultListableBeanFactory

Ex – BeanFactory factory = new XmlBeanFactory(new ClassPathResource(“beans.xml”));

Application Context Hierarchy

  • public interface ApplicationContext extends ListableBeanFactory, HierarchicalBeanFactory, MessageSource, ApplicationEventPublisher, ResourcePatternResolver
  • public interface ConfigurableApplicationContext extends ApplicationContext
  • public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext
  • public abstract class AbstractRefreshableApplicationContext extends AbstractApplicationContext
  • public abstract class AbstractRefreshableConfigApplicationContext extends AbstractRefreshableApplicationContext
  • public abstract class AbstractXmlApplicationContext extends AbstractRefreshableConfigApplicationContext
  • public class ClassPathXmlApplicationContext extends AbstractXmlApplicationContext

Ex – ApplicationContext context = new ClassPathXmlApplicationContext(“beans.xml”);

Bean Factory

  • Bean instantiation/wiring.
  • It exists for backward compatibility.
  • Manual BeanPostProcessor registration
  • Support Lazy loading – It instantiates bean when you call getBean() method.
  • It is OK for testing and non-production use.

Application Context

  • Bean instantiation/wiring.
  • Automatic BeanPostProcessor registration.
  • Automatic BeanFactoryPostProcessor registration.
  • Convenient MessageSource access (for i18n).
  • ApplicationEvent publication – can publish events to beans that are registered as listeners.
  • Support Annotation-based dependency Injection. -@Autowired, @PreDestroy
  • Support many enterprise services such JNDI access, EJB integration, remoting.
  • Support Aggressive loading – It instantiates Singleton bean when the container is started, It doesn’t wait for getBean() to be called.

12

For more detail – watch below video

 

Thanks for reading 🙂

Please Subscribe our you tube channel Almighty Java

What is Application Context ?

  • It is a descendant of Bean Factory and contains some additions functionality.
  • It is an interface for providing configuration information to an application.
  • There are multiple classes provided by spring framework that implements this interface and helps us use configuration information in applications.

All Known Super Interfaces

  • ApplicationEventPublisher
  • BeanFactory
  • HierarchicalBeanFactory
  • ListableBeanFactory
  • MessageSource
  • ResourceLoader
  • ResourcePatternResolver

All Known Sub Interfaces

  • ConfigurableApplicationContext
  • ConfigurablePortletApplicationContext
  • ConfigurableWebApplicationContext
  • WebApplicationContext

All know Abstract Classes

  • AbstractApplicationContext
  • AbstractRefreshableApplicationContext
  • AbstractRefreshableConfigApplicationContext
  • AbstractRefreshablePortletApplicationContext
  • AbstractRefreshableWebApplicationContext
  • AbstractXmlApplicationContext
  • AnnotationConfigApplicationContext
  • AnnotationConfigWebApplicationContext
  • ClassPathXmlApplicationContext
  • FileSystemXmlApplicationContext

All know Classes

  • GenericApplicationContext
  • GenericGroovyApplicationContext
  • GenericWebApplicationContext
  • GenericXmlApplicationContext
  • GroovyWebApplicationContext
  • ResourceAdapterApplicationContext
  • StaticApplicationContext
  • StaticPortletApplicationContext
  • StaticWebApplicationContext
  • XmlPortletApplicationContext
  • XmlWebApplicationContext

Lets Implement

Using class path –

Project structure be like below image

1

add a dependency on pom.xml file –

<dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-context</artifactId>
     <version>4.3.4.RELEASE</version>
</dependency>

bean class “Greetings.java

package com.spring.core;
public class Greetings {
    private String message;
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}

beans.xml file is in classpath so can access using “ClassPathXmlApplicationContext” class

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
        "http://www.springframework.org/dtd/spring-beans-2.0.dtd">  
<beans>
    <bean id="greet" class="com.spring.core.Greetings">
        <property name="message" value="Hello One"></property>
    </bean>
</beans>

Main class

package com.spring.core;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Application {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Greetings greet = (Greetings) context.getBean("greet"); 
        System.out.println(greet.getMessage());
    }
}

Using File System –

2

Everything is like above, only class name will change because previously we are reading file from classpath and now reading from file system so we’ll use “FileSystemXmlApplicationContext” class

package com.spring.core;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class Application {
    public static void main(String[] args) {
        ApplicationContext context = new FileSystemXmlApplicationContext("beans.xml");
        Greetings greet = (Greetings) context.getBean("greet"); 
        System.out.println(greet.getMessage());
    }
}

For more detail, Please watch video –

Thanks for reading 🙂

Please Subscribe our you tube channel Almighty Java