• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Core Java
  • Design Patterns
  • JSP
  • Servlets
  • Building Tools
  • jQuery
  • Spring
  • Hibernate
  • Mongo DB
  • More
    • HTML
    • SCJP
    • AJAX
    • UML
    • Struts
    • J2EE
    • Testing
    • Angular JS

J2EE Reference

  • Home
  • About Us
    • Java Learning Centers
  • Contact Us

Spring

Spring dependency injection with Java configuration

June 19, 2017 By j2eereference Leave a Comment

Here we are going to see how to configure dependency injection in spring with java . In the below example we have two classes MyClass and Myclass2 .There is a dependency of MyClass2 in Myclass . So lets understand how to inject the depended class into another using Spring.

Java
1
2
3
4
5
6
7
public class MyClass {
MyClass2 myClass2;
MyClass(MyClass2 myClass2){
this.myClass2=myClass2;
}
}

Java
1
2
3
4
5
6
public class MyClass2 {
MyClass2(){
System.out.println("Initializing MyClass2");
}
}

Below is the configuration for injecting MyClass2 into MyClass .

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class MySpringConf {
 
    @Bean
    public MyClass myClass() {
        return new MyClass(getClass2());
    }
    
    @Bean
    public MyClass2 getClass2() {
        return new MyClass2();
    }
 
}

Java
1
2
3
4
5
6
7
8
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 
public class SpringConfDemo {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MySpringConf.class);
MyClass myClass = ctx.getBean(MyClass.class);
}
}

Output :

Jun 13, 2017 5:26:43 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@2c634b: startup date [Tue Jun 13 17:26:43 IST 2017]; root of context hierarchy
Initializing MyClass2

Here we can notice that MyClass2 is getting injected in MyClass .

 

 

Related Posts

  • Spring JSR-250 Annotations
  • Injecting singleton class with spring
  • Writing First Aspect in spring
  • What is Aspect Oriented Programming (AOP)
  • Autowired Annotation
  • Constructor injection in spring
  • Bean autowiring
  • LifeCycle call backs in Spring
  • BeanPostProcessor in Spring
  • Initializing list of values using Spring

Filed Under: Spring

What is Spring Boot?

June 16, 2017 By j2eereference Leave a Comment

What is spring boot?

Spring Boot has been built for Rapid Application Development. The goal of Spring Boot is to provide a way to create Java applications quickly and simply, through an embedded server. By default it used an embedded version of Tomcat and hence eliminating need of Java EE containers.

Advantages of Spring Boot

It is a framework to ease the bootstrapping and development of new Spring Applications.

Bootstrapping with defaults included in the configuration / jar-dependencies

Easy to create standalone applications with embedded Tomcat/Jetty/Undertow.

It provides defaults for code and annotation configuration to quick start new spring projects within no time.

Plenty of Spring Boot Starter to quickly get up and running

No code generation and no requirement for XML configuration

It reduces lots of development time and increases productivity.

Features of Spring boot-

No need to manually configure dispatcher servlet, static resource mappings, property source loader, message converters etc.

The different versions of commonly used libraries are pre-selected and grouped in different starter POMs that we can include in your project. By selecting one Spring Boot version we are implicitly selecting dozens of dependencies that we would have to otherwise select and harmonize our self. Example-

There is a large list of bean properties that can be configured through application.properties file without touching java or xml config.

We can package your application as a runnable jar with embedded tomcat included so it presents a self-contained deployment unit

How To create Spring Boot Application

Spring boot Example using maven

Add dependencies as show below in Pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 
   <modelVersion>4.0.0</modelVersion>
   <groupId>SpringBoot</groupId>
   <artifactId>com.j2eereference.springboot</artifactId>
   <version>0.0.1-SNAPSHOT</version>
 
    <parent>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-parent</artifactId>
         <version>1.4.2.RELEASE</version>
     </parent>
 
      <dependencies>
          <dependency>
                 <groupId>org.springframework.boot</groupId>
                 <artifactId>spring-boot-starter-web</artifactId>
           </dependency>
       </dependencies>
 
        <build>
             <plugins>
                 <plugin>
                      <groupId>org.springframework.boot</groupId>
                      <artifactId>spring-boot-maven-plugin</artifactId>
                      <version>1.4.2.RELEASE</version>
                       <executions>
                          <execution>
                              <goals>
                                   <goal>repackage</goal>
                               </goals>
                           </execution>
                        </executions>
                    </plugin>
                 </plugins>
            </build>
</project>

2) ApplicationDemo.java :This class works as an initiator to Spring Boot – as defined by the  @SpringBootApplication annotation – starting a Spring context and the embedded server:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package  com.j2eereference.springboot;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
 @RestController
@SpringBootApplication
public class ApplicationDemo {
    public static void main(String[] args) {
      SpringApplication.run(ApplicationDemo.class, args);
     }
  }

3)HelloController.java

In Spring, REST endpoints are just Spring MVC controllers. The following Spring MVC controller handles a GET request for /hello/springboot and returns the Greeting resource:package com. j2eereference.springboot;

 

1
2
3
4
5
6
7
8
9
10
11
12
13
import org.springframework.web.bind.annotation.RequestMapping;
 
import org.springframework.web.bind.annotation.RestController;
 
@RestController
public class HelloController {
 
   @RequestMapping("/hello/springboot")
    public String getMessage()
    {
      return "Hello, have a great day";
    }
}

4)application.properties : Change the port number(to any value) as mentioned below in this file in case you get exception related to host server while running your boot application.

Server.port=8881

 

To Run Program :

Right click on ApplicationDemo class and select Run as Java Application

 

Check console , your spring boot application has been started(No need to start server as Tomcat is already embedded)

Now Hit Url : http://localhost:8881/hello/springboot

Related Posts

  • Spring bean scopes
  • Spring Bean Factory
  • Spring – Dependency injection

Filed Under: Spring

@import annotation in Spring

June 9, 2017 By j2eereference Leave a Comment

@Import annotation  will be useful if we have multiple spring bean configurations for different modules like Audit ,Transaction etc in a project . In such scenario it is better to import all this configurations into a single configuration class so that there wont be any confusion on creating the beans by referring multiple configuration classes. @Import annotation in spring allows for loading bean definitions from another configuration class

It is very easy to import multiple configuration classes into a single application configuration. Lets understand the usage of @Import with the below example code.

Lets create two bean classes Audit and Transaction

Java
1
2
3
4
5
6
public class Audit {
Audit(){
System.out.println("Inside Audit constructor");
}
 
}

 

Java
1
2
3
4
5
public class Transaction {
public Transaction() {
System.out.println("Inside Transaction constructor"); }
 
}

Below class is to configure Audit related beans, There could be multiple beans . In  our example lets consider only one bean called audit.

Java
1
2
3
4
5
6
7
8
9
10
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class AuditConfig {
  @Bean(name="audit")
    public Audit audit() {
        return new Audit();
    }
}

The same way lets create another configuration class for configuring Transaction related beans.

Java
1
2
3
4
5
6
7
8
9
10
11
12
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class TransactionConfig {
 
    @Bean(name="transaction")
    public Transaction transaction() {
        return new Transaction();
    }
 
}

As of now we have two separate configuration files for Audit and Transaction . It will be difficult to manage if we are not consolidating all the different configuration classes into one. Here comes the use of @Import annotation .

In the below class ApplicationConfig we will import both Audit and Transaction configurations by using @Import annotation.

Java
1
2
3
4
5
6
7
8
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
 
@Configuration
@Import({AuditConfig.class,TransactionConfig.class})
public class ApplicationConfig {
 
}

Below program is to test the import configuration.

Java
1
2
3
4
5
6
7
8
9
10
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 
public class ImportAnnotationDemo {
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(ApplicationConfig.class);
Audit auditBean =(Audit) ctx.getBean("audit");
Transaction transactionBean =(Transaction) ctx.getBean("transaction");
}
}

Output :

Jun 06, 2017 4:19:56 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@2c634b: startup date [Tue Jun 06 16:19:56 IST 2017]; root of context hierarchy
Inside Audit constructor
Inside Transaction constructor

Here you can notice that

  • We are creating single application context by providing the ApplicationConfig.class .
  • All the beans defined in Audit and transaction configurations classes are available with ApplicationConfig class.

Filed Under: Spring

Configuring Spring Lifecycle Callbacks with java

June 8, 2017 By j2eereference Leave a Comment

Spring provides call back methods for the life cycle of the beans. We can have a method in our bean that gets run when the bean is created and we can have a method which will run when the bean is about destroy. Hence we can use this methods for some initialization activity and for clean up activity as well .

We know how to configure lifecycle callbacks using configuration xml file. Here lets find out how to configure the same without using the configuration xml file.

Below is the Bean class which has two methods

init() and cleanUp ().

Java
1
2
3
4
5
6
7
8
public class MyClass {
public void init(){
System.out.println("Inside init");
}
public void cleanUp(){
System.out.println("Inside cleanUp");
}
}

Lets create a class to configure the bean and its callback methods. initMethod is the attribute to configure the initialization method and destroyMethod is the attribute to configure the destroy method.

 

Java
1
2
3
4
5
6
7
8
9
10
11
12
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class mySpringConf {
 
    @Bean(initMethod = "init", destroyMethod = "cleanUp" )
     public MyClass myClass() {
        return new MyClass();
    }
 
}

Below class SpringConfDemo is to test the initMethod and destryMethod configuration.

Java
1
2
3
4
5
6
7
8
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 
public class SpringConfDemo {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(mySpringConf.class);
ctx.close();
}
}

Output:

Jun 06, 2017 1:45:42 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@2c634b: startup date [Tue Jun 06 13:45:42 IST 2017]; root of context hierarchy
Inside init
Jun 06, 2017 1:45:42 PM org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
INFO: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@2c634b: startup date [Tue Jun 06 13:45:42 IST 2017]; root of context hierarchy
Inside cleanUp

Here you can notice that:

  • init method of the bean is getting called as soon as we create the context
  • destroy method is getting called when we close the context.

 

 

Filed Under: Spring

Configuring Spring Bean Scope with java

June 7, 2017 By j2eereference Leave a Comment

In the previous post we have explained how to configure spring with java . Here we are going to see how to configure the bean scope using Java .

Lets understand the bean scope configuration with the below example .

In the below example we have two beans

  • SingletonScopeTest   and
  • PrototypeScopeTest

Java
1
2
3
4
5
public class SingletonScopeTest {
SingletonScopeTest(){
System.out.println("Inside SingletonScopeTest constructor");
}
}

 

Java
1
2
3
4
5
public class PrototypeScopeTest {
PrototypeScopeTest(){
System.out.println("Inside PrototypeScopeTest constructor");
}
}

Now lets create the class MySpringConf for configuring the beans . Here we are defining scope of the beans as below

  • SingletonScopeTest as Singleton and
  • PrototypeScopeTest as prototype

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
 
@Configuration
public class MySpringConf {
 
   @Bean
   @Scope("prototype")
   public PrototypeScopeTest PrototypeScopeTest() {
        return new PrototypeScopeTest();
    }
 
   @Bean
   @Scope("singleton")
   public SingletonScopeTest SingletonScopeTest() {
        return new SingletonScopeTest();
    }
}

Now lets create a class SpringScopeConfDemo to test the above configuration.

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 
public class SpringScopeConfDemo {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MySpringConf.class);
SingletonScopeTest singletonScopeObj1 = ctx.getBean(SingletonScopeTest.class);
SingletonScopeTest singletonScopeObj2 = ctx.getBean(SingletonScopeTest.class);
 
PrototypeScopeTest PrototypeScopeObj1 = ctx.getBean(PrototypeScopeTest.class);
PrototypeScopeTest PrototypeScopeObj2 = ctx.getBean(PrototypeScopeTest.class);
}
}

Output :

Jun 06, 2017 1:14:18 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@2c634b: startup date [Tue Jun 06 13:14:18 IST 2017]; root of context hierarchy

Inside SingletonScopeTest constructor
Inside PrototypeScopeTest constructor
Inside PrototypeScopeTest constructor

Here you can notice that:

  • Scope of the  class  SingletonScopeTest has been configured as singleton and hence the object is getting created only once .
  • Scope of the class PrototypeScopeTest  has been configured as prototype and hence getBean method is creating new objects for every request.

Filed Under: Spring

Spring configuration using java

June 5, 2017 By j2eereference 1 Comment

Spring configuration using java:

Here we are going to see how to  do spring configuration using java , without spring configuration xml . There are some annotations used for configuring the Beans .  You can have one or many configuration classes . The configuration classes should be annotated with @Configuration and all the beans should be annotated with @Bean .

Lets understand this by a sample configuration .

Java
1
2
3
4
5
6
7
8
9
10
11
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class mySpringConf {
 
    @Bean
    public HelloWorld helloWorld() {
        return new HelloWorld();  // instantiate helloWorld object 
    }
}

Java
1
2
3
4
5
6
7
8
9
10
11
public class HelloWorld {
String message;
 
public String getMessage() {
return message;
}
 
public void setMessage(String message) {
this.message = message;
}
}

Java
1
2
3
4
5
6
7
8
9
10
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 
public class SpringConfDemo {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(mySpringConf.class);
HelloWorld helloWorld = ctx.getBean(HelloWorld.class);
helloWorld.setMessage("Welcome to j2eereference.com");
System.out.println(helloWorld.getMessage());
}
}

Output

May 30, 2017 5:17:28 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@2c634b: startup date [Tue May 30 17:17:28 IST 2017]; root of context hierarchy

Welcome to j2eereference.com

Here you can notice the following:

  • Created mySpringConf class for configuring the beans ,Each beans should be annotated as @Bean.
  • Created the AnnotationConfigApplicationContext object by providing the configuration class name ( mySpringConf .class) in the SpringConfDemo class
  • Got the Helloworld object using the getBean method of AnnotationConfigApplicationContext

Bean aliasing 

We can have multiple names for a bean and which can be configured as below.

@Bean(name = { “name-1”, “name-2”, “name-3” })

or

@Bean( { “name-1”, “name-2”, “name-3” })

Java
1
2
3
4
5
6
7
8
9
10
11
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class mySpringConf {
 
@Bean({"name-1", "name-2", "name-3"})
public HelloWorld helloWorld() {
return new HelloWorld();
}
}

and the bean can be accessed by calling getBean() method with bean name as parameter . It could be name-1 ,name-2 or name-3 as below

Java
1
2
3
4
5
6
7
8
9
10
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 
public class SpringConfDemo {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(mySpringConf.class);
HelloWorld helloWorld = (HelloWorld) ctx.getBean("name-1");
helloWorld.setMessage("Welcome to j2eereference.com");
System.out.println(helloWorld.getMessage());
}
}

Bean description

We can configure the bean description with annotation. This is particularly useful when beans are exposed (Example: via JMX) for monitoring purposes.

@Bean
@Description(“Description about the bean”)

Filed Under: Spring

@Required annotation in spring

April 3, 2017 By j2eereference 2 Comments

@Required annotation in spring

We are going to look at how to configure the Spring beans and dependency routing using annotations. Spring provides support for annotation based container configuration. There are some annotations that are used to configure beans and dependency injection. One of them is @Required annotation

We have,

BankApp.java

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.j2eereference.spring;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class BankApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
Bank bank = (Bank)context.getBean("hdfc");
bank.getBranchInfo();
}
}

Here, we are getting “hdfc” bean from spring.xml and calling getBranchInfo().

spring.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?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:p="http://www.springframework.org/schema/p"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
               http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
<bean id="hdfc" class="com.j2eereference.spring.HDFC" >
<property name="branch" ref="branchA" />
</bean>
<bean id="branchA" class="com.j2eereference.spring.Branch" >
<property name="code" value="1234"></property>
<property name="address" value="BranchA Address"></property>
</bean>
<bean id="branchB" class="com.j2eereference.spring.Branch" >
<property name="code" value="1234"></property>
<property name="address" value="BranchB Address"></property>
</bean>
</bean>
</beans>

We have defined “hdfc” to be a bean of type HDFC.java

HDFC.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.j2eereference.spring;
 
public class HDFC implements Bank{
private Branch branch;
 
public Branch getBranch() {
return branch;
}
public void setBranch(Branch branch) {
this.branch = branch;
}
 
@Override
public void getBranchInfo()
{
System.out.println("HDFC Branch code : "+branch.getCode()+"and Address : "+branch.getAddress() );
}
}

HDFC has just a ‘branch’ and getBranchInfo()  method that prints the branch information.

Branch.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.j2eereference.spring;
 
public class Branch {
private int code;
private String address;
public Branch(int code, String address) {
this.code = code;
this.address = address;
}
 
public int getCode() {
return code;
}
 
public void setCode(int code) {
this.code = code;
}
 
public String getAddress() {
return address;
}
 
public void setAddress(String address) {
this.address = address;
}
}

Branch has code and address attributes of type int and String respectively.

Bank.java

1
2
3
4
5
6
7
package com.j2eereference.spring;
 
public interface Bank {
public void getBranchInfo();
 
}

Bank interface is implemented by HDFC.java.

Look at the spring.xml that has “hdfc” bean. It has a property branch that references to another bean ‘branchA’. When we run this, we get the output as :

HDFC Branch code : 1234 and Address : BranchA Address

What happens if we remove the ‘branch’ property from ‘hdfc’ bean?? We have the bean configured which does not have any dependencies specified in the spring.xml. The attribute ‘branch’ in HDFC class will not be assigned any value. When the getBranchInfo() is called, it will give the obvious NullPointerException in the getBranchInfo() method. In real-time applications with thousands of lines code, we never know when we might encounter a NullPointerException like this. We might have the application deployed and running and days down the line we might encounter a NullPointerException because one of the dependencies was not met. So, we have to validate, before the application starts, that all the required dependencies are met. This is where we use the @Required annotation.

In our example we have to let Spring know that ‘branch’ attribute is required. We need to make sure that there is some kind of bean wiring so that ‘branch’ member variable is not null when the application runs. When Spring initializes all the beans, we want Spring to validate that there is some bean that gets assigned to ‘branch’ member variable of ‘hdfc’ bean. In order to do that, we have to configure the HDFC class and tell that ‘branch’ member variable is required. We can  do it on the setter method of the ‘branch’ member variable. This setter has to be run thereby setting some value to the ‘branch’ member variable when the ‘hdfc’ bean is being initialized. If the ‘branch’ is not assigned any value, we want the exception to be thrown, not when the application is running, but while initializing the beans itsels so that we can handle all these errors upfront. To tell spring that ‘branch’ is requires, we use @Required on setter method.

HDFC.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.j2eereference.spring;
 
import org.springframework.beans.factory.annotation.Required;
 
public class HDFC implements Bank{
private Branch branch;
 
public Branch getBranch() {
return branch;
}
@Required
public void setBranch(Branch branch) {
this.branch = branch;
}
 
@Override
public void getBranchInfo()
{
System.out.println("HDFC Branch code : "+branch.getCode()+"and Address : "+branch.getAddress() );
}
}

We can do this on any number of classes. We can mark all the required dependencies with @Required annotation. It tells Spring that ‘branch’ is a required member variable, if it is not set, Spring will not proceed with execution of the application. It will throw an exception.

In addition to marking with @Required annotation, we have to declare a BeanPostProcessor in the spring.xml. When all the beans are being instantiated, it checks for the @Required annotations. If it finds a @Required annotation that is not met, it is the BeanPostProcessor that actually throws the exception. To use the BeanPostProcessor, define the bean in the spring.xml.

spring.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?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:p="http://www.springframework.org/schema/p"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
               http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
<bean id="hdfc" class="com.j2eereference.spring.HDFC" >
</bean>
<bean id="branchA" class="com.j2eereference.spring.Branch" >
<property name="code" value="1234"></property>
<property name="address" value="BranchA Address"></property>
</bean>
<bean id="branchB" class="com.j2eereference.spring.Branch" >
<property name="code" value="1234"></property>
<property name="address" value="Bangalore"></property>
</bean>
<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor" />
</beans>

RequiredAnnotationBeanPostProcessor has a method that gets executed on initialization of each of these beans and checks for the @Required annotation. If it finds any required member variable that is not set, it throws the exception. Note that, in spring.xml, we are not setting ‘branch’ property. We have just added a BeanPostProcessor. When we run this, we get the exception, not from getBranchInfo() but in the bean initialization phase itself, much before the execution of the application. This is how @Required annotation is helpful to validate that all our required dependencies are met.

Filed Under: Spring Tagged With: @Required annotation in spring, spring annotation

Event handling in Spring

July 9, 2015 By j2eereference Leave a Comment

Event handling in Spring

In our previous post we had seen one advantage of using ApplicationContext over BeanFactory(Using MessageSource in Spring). In this post, we explain about one more advantage of using ApplicationContext over BeanFactory, that is Event Handling. There are 3 core elements in Event Handling.

1. Even Publisher – the entity that publishes the event.
2. Even Listener – the entity that listens for the event.
3. Event – the class that contains the information about the event which the Publisher publishes and the Listener listens to.

In case of event handling in Spring, there are interfaces. Spring provides ApplicationListener interface. If we have to write a class that has to listen for an event, it has to implement ApplicationListener interface. We also have ApplicationEventPublisher interface. If we have to write a class that has to publish events, it has to implement ApplicationEventPublisher interface. If we have to write our own custom events, the custom event class has to extend ApplicationEvent class and we can write additional functionality for the event.

We will write a class that listens to all the events that are published.

EventListener.java

1
2
3
4
5
6
7
8
9
10
11
package com.j2eereference.spring.eventHandler;
 
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
 
public class EventListener implements ApplicationListener<ApplicationEvent> {
@Override
public void onApplicationEvent(ApplicationEvent event) {
System.out.println(event.toString());
}
}

EventHandlerDemo.java

1
2
3
4
5
6
7
8
9
10
11
package com.j2eereference.spring.eventHandler;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class EventHandlerDemo {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
EventListener eventListener=(EventListener)context.getBean("eventListener");
}
}

spring.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?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:p="http://www.springframework.org/schema/p"
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.xsd">
<bean id="eventListener" class="com.j2eereference.spring.eventHandler.EventListener"/>
</beans>

 

Output:

1
org.springframework.context.event.ContextRefreshedEvent[source=org.springframework.context.support.ClassPathXmlApplicationContext@16fd0b7: startup date [Thu Jul 09 20:24:06 IST 2015]; root of context hierarchy]

We will look at EventListener .java that listens to events.

EventListener implements ApplicationListener interface and has to implement the method onApplicationEvent (). Just to keep it simple, we have a sysout statement that prints the event itself. This method is called by Spring when any application event is published. It takes in a parameter of ApplicationEvent. Whatever the code we write inside this method, gets published upon every event that is published in the spring framework. Of course the event itself is passed as parameter on every call.

What happens is, a context has been created in EventHandlerDemo.java and is refreshed and that event is published by the spring framework. The listener class (EventListener ) has listened to that event. Upon listening to that event, it executed onApplicationEvent() method where it prints the actual event itself. In the output message, we can see the event call that has been printed, the event being ContextRefreshedEvent. This event has been published. Our EventListener class has listened to this and  did a toString() to print the event. In the output, we can also see the startup date and the root of the context hierarchy. Basically  this message is  the toString() of the  ContextRefereshedEvent.

Publishing custom events

What if we want to publish our own events?? There are two things we need to do in order to publish our own events. 1. We need to write an event class
2. Have that event published in any of the beans

EventListener.java

1
2
3
4
5
6
7
8
9
10
11
12
package com.j2eereference.spring.customEvent;
 
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
 
public class EventListener implements ApplicationListener {
 
@Override
public void onApplicationEvent(ApplicationEvent event) {
System.out.println(event.toString());
}
}

DisplayEvent.java – our custom event class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.j2eereference.spring.customEvent;
 
import org.springframework.context.ApplicationEvent;
 
public class DisplayEvent extends ApplicationEvent {
public DisplayEvent(Object source) {
super(source);
}
public String toString()
{
return "Custom Event called";
}
}

MyClass .java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.j2eereference.spring.customEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
 
public class MyClass implements ApplicationEventPublisherAware{
private ApplicationEventPublisher publisher;
 
public void display()
{
DisplayEvent customEvent = new DisplayEvent(this);
publisher.publishEvent(customEvent);
}
 
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
this.publisher=publisher;
}
 
}

EventDemo.java

1
2
3
4
5
6
7
8
9
10
11
12
package com.j2eereference.spring.customEvent;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class EventDemo {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
MyClass customEventTest=(MyClass)context.getBean("myClass");
customEventTest.display();
}
}

Spring.xml

XHTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?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:p="http://www.springframework.org/schema/p"  
    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.xsd">  
<bean id="myClass" class="com.j2eereference.spring.customEvent.MyClass"/>
<bean id="EventListener" class="com.j2eereference.spring.customEvent.EventListener"/>
</beans>

Output:

1
2
org.springframework.context.event.ContextRefreshedEvent[source=org.springframework.context.support.ClassPathXmlApplicationContext@1764be1: startup date [Thu Jul 09 22:39:39 IST 2015]; root of context hierarchy]
Custom Event called

Any custom event class should extend ApplicationEvent. ApplicationEvent is the base event class that Spring provides.  When we extend this class, we have to override the constructor and make sure that super() is called. To keep it simple, we override the toString() method and print our own custom message here so that the event gets published and caught by EventListener because we are doing event.toString() in the Listener.  We have the event now. Lets see how to publish it.

We will publish the event inside dispay() of MyClass class. In order to publish an event, we need to have a Publisher. Spring provides an interface called ApplicationEventPublisher. We use this interface to publish the event.

We have added one more member variable ‘publisher’ of type ApplicationEventPublisher. In the display() method, we create an instance of DisplayEvent, passing the current object(this) as a parameter. Because this is how we have defined the constructor of DisplayEvent class. We call publishEvent() method on the member variable ‘publisher’ passing the customEvent object as the parameter. But how does ‘publisher’ gets initialized? We have not added bean property in spring.xml.  In order to get a handle to ‘publisher’ member variable, we implement an interface called ApplicationEventPublisherAware, irrespective of the type of the ‘publisher’. When spring finds any bean that implements this interface, it provides an ApplicationEventPublisher to that bean and to get that Publisher, spring uses setApplicationEventPublisher() method to give us the Publisher.  This method takes in a parameter of type ApplicationEventPublisher. We override this method and set our member variable ‘publisher’ to the parameter value.

When we run this, we can see ‘Custom Event called’ in the output. What happens is, the context object gets initialized and we see ContextRefreshedEvent being listened by our EventListener,  we have instantiated a customEvent which is being published by the publisher and caught by EventListener.

Filed Under: Spring

Using MessageSource in Spring

July 8, 2015 By j2eereference Leave a Comment

Using MessageSource in Spring

Messaging support and Internationalization is provided by Spring ApplicationContext and this is one of the advantages of using Application Context over BeanFactory. If we have different messages that need to be displayed in application UI and we would not want those messages to be inside the code, we keep those messages in properties file and then refer to these texts inside the properties file. Spring provides support for this. We can have a properties file which consolidates all the key and value pairs and then we specify the key in our application to refer to that text which is assigned to that key in the properties file.  Let us see how we can use this support for Messages in Spring.

mymessages.properties

1
greeting=Hello!

We have the message ‘Hello!’  saved inside a properties file and we have given it  a key of ‘greeting’. We will use this key-value pair and print ‘Hello!’ message in our program.

The first thing we need to have in order to have Messaging Support enabled is to have a message source bean defined in the application.

 spring.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?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:p="http://www.springframework.org/schema/p"  
    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.xsd">  
  
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>mymessages</value>
</list>
</property>
</bean>
<context:annotation-config/>
<context:component-scan base-package="com.j2eereference.spring"></context:component-scan>
</beans>

The bean added to support the message service the bean with id=”messageSource” and the class ‘ResourceBundleMessageSource’ (give the fully qualified name as mentioned in spring.xml). This class is provided by Spring. It helps us pick messages from properties file. This bean needs some more configuration – we need to tell the bean where the properties file is. To do that, we have added a property tag with name ‘basenames’ and within which we define the list of properties file names(without .properties extension). We have only one properties file in our example. If there are multiple properties files, we can list out all the properties file over here. This is what The messageSource is going to look at when it has to pull up messages.

MessageSourceDemo.java

1
2
3
4
5
6
7
8
9
10
11
12
package com.j2eereference.spring;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class MessageSourceDemo{
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
System.out.println(context.getMessage("greeting",null,"Default Greeting", null));
}
}

Output:

Hello!

The ‘context’ object has a method called getMessage(). There are different signatures for this method. Lets look into the one that is used here. It takes four parameters –
First parameter – the name of the property that we need to retrieve from the properties file. ‘greeting’ in this example.
Second parameter – A string of object in case the message takes in some parameters. We will look at parameter messages later. Since we don’t have parameter in our message and it is a simple text, we will keep it null.
Third Parameter – The default message that it needs to return in case it does not find a message that we are looking for.’Default Greeting’ in our example. This message will be shown if a corresponding message for the ‘greeting’ key is not found in any of the properties files.
Fourth parameter – the locale for which we are going to get the message. We will keep it null for now and explain it later.

Injecting MessageSource into a bean:

Here lets understand how to inject the MessageSource into a bean with the below example

mymessages.properties

1
greeting=Hello Good morning !

spring.xml

XHTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?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:p="http://www.springframework.org/schema/p"  
    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.xsd">  
<bean id="Greetings" class="com.j2eereference.spring.messageSource.Greetings" >
<property name="messageSrc" ref="messageSource"/>
</bean>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>mymessages</value>
</list>
</property>
</bean>
<context:annotation-config/>
<context:component-scan base-package="com.j2eereference.spring"></context:component-scan>
</beans>

 

Greetings.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.j2eereference.spring.messageSource;
 
import org.springframework.context.MessageSource;
 
public class Greetings {
MessageSource messageSrc;
 
public MessageSource getMessageSrc() {
return messageSrc;
}
 
public void setMessageSrc(MessageSource messageSrc) {
this.messageSrc = messageSrc;
}
public void display()
{
System.out.println(this.messageSrc.getMessage("greeting", null,"Default Greeting", null));
}
 
}

MessageSourceDemo.java

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.j2eereference.spring.messageSource;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class MessageSourceDemo {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
Greetings greetings= (Greetings)context.getBean("Greetings");
greetings.display();
}
}

Output:

1
Hello Good morning !

Using placeholder in MessageSource:

This is fine but how do we replace the sysout that prints the branch information, using message source? As mentioned earlier, the second parameter of the getMesssage() is a string object that in case the message takes in some parameters. Now lets add one more entry in the properties file to print the branch information using message source.

mymessages.properties

1
bank.information=HDFC Branch code : {0} and Address : {1}

MessageSourceDemo.java

1
2
3
4
5
6
7
8
9
10
11
12
package com.j2eereference.spring.messageSource;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class MessageSourceDemo {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
System.out.println(context.getMessage("bank.information",new Object[]{"0001","Bangalore , India"},"Default Greeting", null));
}
}

Output:

1
Branch code :0001 and Address : Bangalore , India

Here the message is picked up from the properties file and it also does the parameter substitution.

Filed Under: Spring

Component annotation in spring

July 7, 2015 By j2eereference Leave a Comment

Component annotation in spring:

In previous posts, we have seen how to do wiring of beans inside Spring using annotations. Most of the annotations had a common requirement that the bean which gets injected into, needs to be configured in the xml. In this post we explain about annotation that declares a class as a bean so that we don’t have to even add <bean></bean> tag in the xml. We can have the configurations inside the class itself using annotations. In order to do this, we have to tell Spring what classes are going to be bean and what classes are not. We use @Component annotation to tell Spring that, a particular class is going to be a bean.

Hdfc.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.j2eereference.spring;
 
import javax.annotation.Resource;
import org.springframework.stereotype.Component;
 
@Component
public class Hdfc implements Bank{
private Branch branch;
 
public Branch getBranch() {
return branch;
}
@Resource(name="branchB")
public void setBranch(Branch branch) {
this.branch = branch;
}
 
@Override
public void getBranchInfo()
{
System.out.println("HDFC Branch code : "+branch.getCode()+" and Address : "+branch.getAddress() );
}
}

Defining a class with @Component is equivalent to configuring the bean inside xml. @Component creates the bean with name of the class in lower class.

spring.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?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:p="http://www.springframework.org/schema/p"  
    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.xsd">  
<bean id="branchA" class="com.j2eereference.spring.Branch" >
<property name="code" value="1234"></property>
<property name="address" value="BranchA Address"></property>
</bean>
<bean id="branchB" class="com.j2eereference.spring.Branch" >
<property name="code" value="5678"></property>
<property name="address" value="BranchB Address"></property>
</bean>
<context:annotation-config/>
<context:component-scan base-package="com.j2eereference.spring"></context:component-scan>
</beans>

Now look at the Branch related beans in xml. We have defined Branch with 2 different names. That is we have two instances of the Branch bean with different names  – branchA and branchB. What happens if we define a bean using @Component annotation and not in the xml, we cannot have more than one instance of the bean. This is obvious because a class with one name can create only instance, we cannot have a different name for it. If we want another instance, we have to create another class with different name and make it a bean using @Component. This is one of the disadvantages of using annotations and advantage of using xml configuration.  This is what happens if we add @Component annotation inside Branch. Hence lets not use it inside Branch class, we will retain the xml configuration for Branch to have different instances for Branch.

Also, spring xml needs to know that we have beans inside the code that it needs to look for. It has to not only look for the beans defined in the xml, it also has to look for the beans defined inside the code using annotations. We need to ask Spring to scan through all the classes and then identify what annotations mark certain classes as beans. In order to do this, we add <context:component-scan> tag. This tag tells Spring that it needs to scan for components, the components being beans marked as @Component. We have to enter the property ‘base-package’. This package tells Spring to which package it has to scan to look for the @Component annotation. We want to it to scan only a particular package because it is more efficient than scanning everything. So we restrict the search to a certain package. It has some other advantages as well which we will see later.

In our main method, we don’t have to do any change. When Spring finds @Component, it registers the class as a bean with same name as the the class (first letter lower-cased).

BankApp.java

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.j2eereference.spring;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class BankApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
Bank bank = (Bank)context.getBean("hdfc");
bank.getBranchInfo();
}
}

So we are set to run this.
Output:
HDFC Branch code : 5678 and Address : BranchB Address

The component-scan tag searches for other annotations as well apart from @Component. These annotations are called as stereotypes. The concept of stereotypes is, when we write enterprise applications in Spring, we would have some standard beans that perform some standard roles. We would have a data object, a service class, a view, a controller etc. All these are stereotypical roles that Spring beans perform in any enterprise application. We have Spring annotations that let us define a bean to perform one of those roles.

Suppose Hdfc.java to be service layer class. Instead of @Component, we could have @Service annotation. Even if we replace now @Component with @Service, it is going to work the same way and produce the same result. But @Service gives additional information to Spring that it is a service bean.

If Hdfc.java were a data object, we could use @Repository which works the same way and tells spring that it is a data object.

@Controller tells spring that it is a Controller class.

The functionality of these stereotyped annotations is no different from @Component. But @Component is something generic and tells spring that it is a bean. The stereotyped annotations give an additional  information about what role the bean performs.

Advantage of using stereotyped annotations:
It adds a level of of documentation. We look at the bean and know what role it performs.

Filed Under: Spring

  • Go to page 1
  • Go to page 2
  • Go to page 3
  • Go to Next Page »

Primary Sidebar

FOLLOW US ONLINE

  • View J2eereference-166104970118637’s profile on Facebook
  • View j2eereference’s profile on Twitter
  • View j2eereference’s profile on LinkedIn

Subscribe by email

Recent posts

  • What is parallel Stream
  • reduce method of the Stream class
  • Difference between the findFirst() and findAny() method
  • intern() method of String class
  • SOLID – Five principles of object-oriented software design
  • Java Coding Best Practices
  • How to use lambda expression effectively
  • Enhanced pseudo-Random Number Generators in java17
  • How to use Foreign-Memory Access API
  • Pattern Matching for instanceof
  • Text Blocks – Feature added in Java17
  • Record – The new feature added in java 17
  • What is Sealed Class
  • Features added in Java 17
  • Java Buzzwords

Footer

Core Java
Design Patterns
JSP
Servlets
HTML
Building Tools
AJAX
SCJP
jQuery
Testing
Spring
UML
Struts
Java Centers
Java Training
Home
About Us
Contact Us
Copyright © j2eereference.com. All right reserved.