• Skip to primary navigation
  • Skip to 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 JSR-250 Annotations

July 6, 2015 By j2eereference Leave a Comment

Spring JSR-250 Annotations:

JSR-250 is a standard, Java Specifications Request that defines all the standard annotations that would apply across different technology and different frameworks. Spring supports some of the standard JSR-250 annotations

@Resource : 
@Resource is another annotation that can be used to inject dependencies into member variables of a class. @Resource annotation can do a standard dependency injection by name.
We have HDFC.java that has a member variable’branch’.

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 javax.annotation.Resource;
 
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() );
}
}

And we have the interface Bank.java

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

BankApp.java  that gets the ‘hdfc’ bean in the application context.

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();
}
}

spring.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?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="5678"></property>
<property name="address" value="BranchB Address"></property>
</bean>
</beans>

In the spring.xml, notice that we have not initialized the ‘branch’ property of ‘hdfc’ bean. But we have injected the dependency using @Resource annotation on the setBranch() method (setter method of ‘branch’ member variable). As already mentioned above, it does the auto-wiring by name, so we specify name=”branchB”. Thus, the member variable ‘branch’ gets initialized with ‘branchB’ bean. When we run this,

Output:
HDFC Branch code : 5678 and Address : BranchB Address

There are some defaults that we can look here. Suppose we do not specify the name for the annotation, spring will look for the bean with same name as the member variable and does the dependency injection. This is how @Resource is similar to auto-wire by name.

@PostConstruct and @PreDestroy.

Suppose we have an init method initializeHDFC() and destroy method destroyHDFC() in our HDFC.java. We want these methods to be called when the HDFC bean itself is initialized and destroyed respectively.

If we had to configure this using XML, we would have init and destroy methods for the hdfc definition or we would have to implement the initializing bean and disposable bean interfaces and specify the right names for the methods. Here, we have custom names for init and destroy method names and we are not even entering the configuration in the xml. We will use the annotations for initializing and destroying the HDFC bean.  These annotations are @PostConstruct and @PreDestroy. The names are self explanatory. @PostConstruct is executed soon after the bean is initialized and @PreDestroy is executed just before the bean is destroyed. In order to execute the PreDestroy() method, make sure you register the shutdown hooks in the application context.

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
26
27
28
29
30
31
32
33
34
35
package com.j2eereference.spring;
 
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
 
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() );
}
@PostConstruct
public void initializeHDFC()
{
System.out.println("Initializing HDFC...");
}
@PreDestroy
public void destroyHDFC()
{
System.out.println("Destroying HDFC...");
}
}

Notice the changes in BankApp.java to register the shutdown hooks.
BankApp.java

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

Output:
Initializing HDFC…
HDFC Branch code : 5678 and Address : BranchB Address
Destroying HDFC…

 

Related Posts

  • Spring dependency injection with Java configuration
  • What is Spring Boot?
  • @import annotation in Spring
  • Configuring Spring Lifecycle Callbacks with java
  • Configuring Spring Bean Scope with java
  • Spring configuration using java
  • @Required annotation in spring
  • Event handling in Spring
  • Using MessageSource in Spring
  • Component annotation in spring

Filed Under: Spring

Injecting singleton class with spring

June 18, 2015 By j2eereference Leave a Comment

Injecting singleton class with spring

There are some differences between Singleton as a design pattern and Spring’s singleton scope. Singleton as a design pattern will ensure that you have only one object of class defined per Class Loader. But in case of Spring’s singleton scope ,spring will create one instance per Spring Context.

First lets see the common issue we face when we inject singleton class properly.  Here in this example we have a singleton class as below and we have configured the same bean in two different configuration files,spring1.xml and spring2.xml .

Singleton.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
29
30
package com.j2eereference.spring;
 
public class Singleton {
private static Singleton singleton;
String name="ABC";
 
private Singleton(){
System.out.println("Inside constructor ");
}
 
public static Singleton getInstance(){
 
if(singleton == null){
return new Singleton();
}
else
return singleton;
}
 
public void printInfo(){
System.out.println("Name is : " +name);
 
}
 
public void setName(String name) {
this.name = name;
}
 
 
}

Spring1.xml

XHTML
1
2
3
4
5
6
7
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">  
   <bean id="singleton" class="com.j2eereference.spring.Singleton"/>
</beans>

spring2.xml

XHTML
1
2
3
4
5
6
7
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">  
    <bean id="singleton" class="com.j2eereference.spring.Singleton"/>
</beans>

Demo.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.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class SpringDemo {
public static void main(String[] args) {
AbstractApplicationContext context = new ClassPathXmlApplicationContext(
"spring1.xml");
 
AbstractApplicationContext context2 = new ClassPathXmlApplicationContext(
"spring2.xml");
 
Singleton singleton= (Singleton)context.getBean("singleton");
singleton.setName("XYZ");
singleton.printInfo();
 
Singleton singleton2= (Singleton)context2.getBean("singleton");
singleton2.printInfo();
 
}
}

output
Jun 18, 2015 11:56:42 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@5c07612a: startup date [Thu Jun 18 11:56:42 IST 2015]; root of context hierarchy
Jun 18, 2015 11:56:42 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring1.xml]

Inside constructor
Jun 18, 2015 11:56:42 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@555fbf35: startup date [Thu Jun 18 11:56:42 IST 2015]; root of context hierarchy
Jun 18, 2015 11:56:42 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring2.xml]

Inside constructor
Name is : XYZ
Name is : ABC

 

Here you can notice that spring has created two different objects when it load the spring.xml files .

If you want to get only one instance of a particular class irrespective of multiple spring contexts ,we can make use of factory-method attribute as below.

 

XHTML
1
2
3
4
5
6
7
8
9
10
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
  
   <bean id="singleton" class="com.j2eereference.spring.Singleton" factory-method="getInstance">
    
    </bean>
</beans>

If you run the same Demo.java with the above spring configuration you will get the below output

Output
Jun 18, 2015 12:01:40 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@498ab963: startup date [Thu Jun 18 12:01:40 IST 2015]; root of context hierarchy
Jun 18, 2015 12:01:40 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring1.xml]

Inside constructor
Jun 18, 2015 12:01:40 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@de5770f: startup date [Thu Jun 18 12:01:40 IST 2015]; root of context hierarchy
Jun 18, 2015 12:01:40 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring2.xml]

Name is : XYZ
Name is : XYZ

Now spring created only one object .

Related Posts

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

Filed Under: Spring

Writing First Aspect in spring

June 17, 2015 By j2eereference Leave a Comment

Writing First Aspect in spring

We have explained what is Aspect oriented Programming in our previous article What is AOP. To start writing first aspect, lets use the Bank business case where we will have some Bank service that will retrieve some bank information(say for example address). We will have a main class that will get the instance of this business service using Spring dependency injection and call the method to get the bank information.

HDFC.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.j2eereference.spring.model;
 
public class HDFC {
private String address;
 
public String getAddress() {
return address;
}
 
public void setAddress(String address) {
this.address = address;
}
}

CITI.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.j2eereference.spring.model;
 
public class CITI {
private String address;
 
public String getAddress() {
return address;
}
 
public void setAddress(String address) {
this.address = address;
}
}

 

BankService.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.j2eereference.spring.service;
 
import com.j2eereference.spring.model.CITI;
import com.j2eereference.spring.model.HDFC;
 
public class BankService {
private HDFC hdfc;
private CITI citi;
public HDFC getHdfc() {
return hdfc;
}
public void setHdfc(HDFC hdfc) {
this.hdfc = hdfc;
}
public CITI getCiti() {
return citi;
}
public void setCiti(CITI citi) {
this.citi = citi;
}
}

Configure the beans in spring.xml. For the BankService bean lets use auto-wiring byName to inject the dependencies since the names of beans and the properties in service can be retained same.

spring.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
 
<bean name="hdfc" class="com.j2eereference.spring.model.HDFC">
<property name="address" value="HDFC Address"></property>
</bean>
<bean name="citi" class="com.j2eereference.spring.model.CITI">
<property name="address" value="CITI Address"></property>
</bean>
<bean name="bankService" class="com.j2eereference.spring.service.BankService" autowire="byName">
</bean>
 
</beans>

Now instantiate the service bean in the main method and run it.

BankApp.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.j2eereference.spring;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
import com.j2eereference.spring.service.BankService;
 
public class BankApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
BankService bankService = context.getBean("bankService", BankService.class);
System.out.println(bankService.getHdfc().getAddress());
}
}

Output:
HDFC Address

We will use this execution flow to write our Aspect. Lets use a simple Logging aspect, that is to print a log message before a particular method is called. In this example, we shall print a log message every time getAddress() of HDFC.java is called.

The first step is to create the Aspect.

LoggingAspect.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.j2eereference.spring.aspects;
 
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
 
@Aspect
public class LoggingAspect {
@Before("execution(public String getAddress())")
public void loggingAdvice()
{
System.out.println("Advice run. Get address method is called");
}
 
}

We have used @Aspect annotation to let Spring know that LoggingAspect class should be treated as an aspect. loggingAdivce() is the method that we want to execute before the execution of getAddress() method. We have used @Before annotation to tell  Spring that, before executing loggingAdvice() execute getAddress() method.

This is just creating the Aspect and configuring the Aspect behavior. We have to tell Spring that we have AOP in place with a special annotation in spring.xml. Also include the LoggingAspect bean definition in order to see LoggingAspect as an aspect with PostProcessor or any other bean.

spring.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<aop:aspectj-autoproxy />
 
<bean name="hdfc" class="com.j2eereference.spring.model.HDFC">
<property name="address" value="HDFC Address"></property>
</bean>
<bean name="citi" class="com.j2eereference.spring.model.CITI">
<property name="address" value="CITI Address"></property>
</bean>
<bean name="bankService" class="com.j2eereference.spring.service.BankService" autowire="byName" />
 
<bean name="loggingAspect" class="com.j2eereference.spring.aspects.LoggingAspect" />
 
</beans>

<aop:aspectj-autoproxy />
This is included to tell Spring that we are using AOP, if there are any aspects make sure the aspect methods are executed as configured.

Output:
Advice run. Get address method is called
HDFC Address

loggingAdvice() is called before calling the getAddress() on the HDFC class. Notice that getAddress() is common in both HDFC.java and CITI.java. In @Before(“executing(public String getAddress())”), we have no mention of HDFC.java. It is the bankService instance that is getting the HDFC object and calling getAddress() on it in BankApp.java.

In BankApp.java, what if we replaced
System.out.println(bankService.getHdfc().getAddress());
with
System.out.println(bankService.getCiti().getAddress());

Output would be:
Advice run. Get address method is called
Citi Address

Notice that LoggingAspect runs for CITI as well. Because we have not asked LoggingAspect to be specific for HDFC. We have configured it to execute whenever ‘public String getAddress()’ is called no matter which class the method belongs to.

Filed Under: Spring

What is Aspect Oriented Programming (AOP)

June 16, 2015 By j2eereference 1 Comment

What is Aspect Oriented Programming

Aspect Oriented Programming Concepts

Aspect Oriented Programming(AOP) is not just a feature that Spring provides, it is actually a model of programming itself.

Before we actually go into AOP, lets recap functional programming. If you ever had written code in older programming languages like C, you would know what it is.
Fun1

In functional programming, we break down the problem into smaller functions. Each function accomplishes a particular unit of work. A function can call other function and that is how they communicate. In simple words, a simple program consists of many functions which are called based on the logic of the solution. When the last function is called and it completes execution, that is when the program ends as well.  So, this is the way we think of functions when we write code in functional programming.

The problem here is that, in real-time applications, the design involves complexity and we would have large number of functions and lots of inter-dependency between the functions. The above graph could become really messy.

In some situations, we would get better designs if we used object-oriented programming instead of functional programming.

obj

Unlike functional programming, we don’t think of functions in object-oriented programming when solving a problem. We think of individual entities as objects. We write objects that reflect the different entities in the problem space. Each object would contain the member variables as well as the methods. Thus, we encapsulate the entities and can write more complex solution  because we would have a cleaner design and separation of concerns. This may look fine, but there is a problem here as well. Not all the tasks that we want our program to do can be classified as objects!!

obj2.lpg

We have a common method logMessage() across all the objects here. We want this method to be run and included in 3 different objects. What happens in a complex solution? No matter how many objects need the logMessage(), we would include it in each of those objects. This is not really a good design because we repeat the code by including same method in all the objects.

How to refine this design? One approach is to take that common method out and create a separate object. We cannot leave that method floating on its own. We have to include it in an object.

logger

Now the logMessage() is included inside Logger object. ObjectX, ObjectY and ObjectZ do not have that logMessage() inside them anymore. Instead, what happens is that, whenever a logMessage() needs to be called, it would reference Logger object and then do a logMessage() on the referenced object. It would either have a dependency and create a new Logger object instance and call the logMessage() OR it would be a static method which would be called directly. Logger class could also be a parent class that would inherit logMessage() into each of our objects that need this method.

This also may look good. But still there are problems:

First problem is that, suppose you are doing a design and want to draw a diagram that depicts the relationship between different objects and you want to know the objects that are really important, based on how they are connected to other objects. That is, the objects that are connected to other objects, the maximum. Now if we write a diagram for our above design, it is most likely that, the most important objects would not be our business objects but probably the Logger object. Because every object that needs a Logger object, has a dependency on this Logger object. It is not really a good idea to have this kind of dependency to something that is not really a part of your business problem. We have too many dependencies to this Logger object which is not adding any business value. It is doing something else like a support role. That would be a problem.

1. Too many relationships to the cross-cutting objects – Cross-cutting objects here mean that the objects that concern other different objects in our problem domain. Ex : Logger object here.
2. Code is still required in all methods that need – we still need the code in other objects to make a call to the logMessage(). We may have removed the method in dependent object but we still have the code that makes a call to logger functionality.
3. All cannot be changed at once – Suppose we want a change in bulk. We want a common different method. In that case, we have to make changes in all the business objects to call the new Logger method instead. Of course this can be solved using some more intelligent design, have an interface and plug-in the different logger method implementations. But, if that cannot be solved using an interface, we would need to go to each of those classes and make code changes.

Why are these problems Significant?

Because the whole concept of having a cross-cutting object is very common in the software design. This problem may occur in all the places, wherever there are cross-cutting concerns.

Cross-cutting concerns: You have some functionalities that need to be used by objects and they may not be part of your problem domain. It could be infrastructure related, security related etc. Common examples of cross cutting concerns in a real world application are :
1. Logging
2. Transactions
3. Security

We will have to implement these features based on the business problem and the number of users. Since this is a common problem, there are ways to deal with it. AOP is one of the elegant ways to solve this problem.

How things change with AOP?

AOP

We have removed the common functionality in objects ObjectX, ObjectY and ObjectZ for logging. Now we create a new Aspect called Logging Aspect. For now, let us think this Logging Aspect to be a class with special privileges(We will see the details later). Similarly we can have many other aspects as needed. May be a Transaction Aspect if we are going to implement Transaction-related cross-cutting concerns as well.

How is this different from having a separate object? We could have an object for Logging, an object for Transaction etc. The difference here is – After creating these aspects, we do not reference these aspects in our code (ie., in the classes ObjectX, ObjectY and ObjectZ). We do not instantiate a logging/Transaction object and make a method call. Instead, we would define a Configuration(Aspect Configuration) that tells, which methods and which objects these aspects should apply to. This is what is different from the traditional object-oriented programming, where we take these common functionalities, create a separate class, have objects and then reference those objects inside the objects that need those functionalities. Instead, we have aspects, we write the configuration that tells which aspects apply to which methods of which classes. This is something that Spring helps us with.

What happens here is, we have particular methods in each of the classes X, Y and Z. We have a Logging Aspect that has logMessage() method. We want this method to be called just before each of these methods that we are concerned about are called. Example : We want logMessage() to be called before Methods() in each of these classes is called. Say, we have 5 methods in ObjectX, 3 methods in ObjectY and just one method in ObjectZ. We want to execute logMessage() before any of these methods are executed. What we do in this case is, we write the Aspect Configuration and say, “For all the methods inside ObjectX, ObjectY and ObjectZ, make sure logMessage() also runs whenever those methods are called”. This is something we can tell Spring to do and Spring will make sure that the logging method is called just before those methods that are configured in Aspect Configuration are executed.

So, ‘before’ is just one of the ways we can apply aspects. This model is similar to Interceptors in Struts, servlet-filters and triggers in databases.  Now we can think of AOP as : we have separate pieces of features to be run before some other functionalities are executed and they are not configured in the code, they are actually separate configuration files. Since, they are all residing inside the Spring container, Spring makes it easy for that to happen. Spring reads these configurations and whenever it senses that some particular methods are called and executed, just before execution happens, the configured aspects are executed first by the Spring so that the given configuration is achieved.

Advantages of AOP:

1. Can have different configurations for different methods : If we want ObjectX to have logging and ObjectY to not have logging, we can achieve it simply by doing the right Aspect Configurations.
2. Down the line, if we want to change any configuration, we don’t have to go the object and change the code. Instead, change the configuration in Aspect Configurations. We don’t have to make any changes in the method call. This makes it easy for us to add/remove and make any change as such.
3. We can make bulk changes as well, with just changing the Aspect Configurations.

Wrapping Aspects around methods: Suppose we have a method to execute after a particular method executes, we can do the ‘after’ configuration in the Aspect Configurations to run the method after the particular method runs.

target

To be kept in mind is that, we can control the flow using different aspect configurations.

Steps in AOP:
1. Write Aspects : Identify the cross-cutting concerns and write them.
2. Configure where Aspects should be applied : Select the methods ‘before’/’after’ which the Aspects have to run.

In our upcoming posts we will see programming examples to implement AOP.

Filed Under: Spring Tagged With: AOP, Aspect OrientedProgramming, Aspects

Autowired Annotation

June 8, 2015 By j2eereference Leave a Comment

Autowired Annotation

Spring provides support for annotation based container configurations.  On of them is @Autowired annotation .In one of our earlier posts, we had talked about Bean Auto-wiring : ByName, ByType and ByConstructor ( http://209.97.166.197/2015/06/bean-autowiring/ ). This post is about wiring the dependencies using Annotations, which we do by using @Autowired annotation.

In order to wire any dependency, we specify the the @Autowired into the member variable. This is actually auto-wiring by type which we have seen in our earlier posts which is sometimes ambiguous, depends on what types of beans we have specified in the spring.xml. However, @Autowired has a few other tricks that can make it less ambiguous.

Lets look at the example.

Bank.java is an interface

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

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
29
30
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;
}
 
}

HDFC.java is the class where we wire the dependency for the member variable of type ‘Branch’

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

Note that we have made ‘branch’ member variable of the bean as auto-wired.

spring.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?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="bank" class="com.j2eereference.spring.HDFC" >
</bean>
<bean id="branchA" class="com.j2eereference.spring.Branch" >
<property name="code" value="1234"></property>
<property name="address" value="Bangalore"></property>
</bean>
<bean class="org.springframework.beans.factoty.annotation.AutowiredAnnotationBeanPostProcessor"></bean>
</beans>

@Autowired is a BeanPostPrecessor and hence we have to declare it in the spring.xml.

Now we have ‘hdfc’ bean and a ‘branchA’ bean.We have mentioned ‘branch’ member variable as auto-wired and we have supplied a bean ‘branchA’ whose type matches the type of the auto-wired member variable. It is very straightforward for Spring to know that it should auto-wire ‘branch’ member variable with ‘branchA’ bean.

It produces the below output:

HDFC Branch code : 1234 and Address : Bangalore

Now what happens if I declare multiple beans of type ‘Branch’?

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"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
               http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
<bean id="bank" class="com.j2eereference.spring.HDFC" >
</bean>
<bean id="branchA" class="com.j2eereference.spring.Branch" >
<property name="code" value="1234"></property>
<property name="address" value="Bangalore"></property>
</bean>
<bean id="branchB" class="com.j2eereference.spring.Branch" >
<property name="code" value="1234"></property>
<property name="address" value="Bangalore"></property>
</bean>
<bean id="branchC" class="com.j2eereference.spring.Branch" >
<property name="code" value="1234"></property>
<property name="address" value="Bangalore"></property>
</bean>
<bean class="org.springframework.beans.factoty.annotation.AutowiredAnnotationBeanPostProcessor"></bean>
</beans>

Note that we added two more beans ‘branchB’ and ‘branchC’ of type ‘Branch’. Now there three beans of type ‘Branch’. When we run this, we get an exception saying ‘Error creating bean with name ‘bank’: Injection of auto-wired dependencies failed. It means that the Spring is not able to find which bean it needs to be injected.

What we can do here is change the name of one of the beans to be same the the name the member variable. For example, the name of member variable is ‘branch’,so change any one of the bean names to be ‘branch’ and run it.

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"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
               http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
<bean id="bank" class="com.j2eereference.spring.HDFC" >
</bean>
<bean id="branch" class="com.j2eereference.spring.Branch" >
<property name="code" value="1234"></property>
<property name="address" value="Bangalore"></property>
</bean>
<bean id="branchB" class="com.j2eereference.spring.Branch" >
<property name="code" value="1234"></property>
<property name="address" value="Bangalore"></property>
</bean>
<bean id="branchC" class="com.j2eereference.spring.Branch" >
<property name="code" value="1234"></property>
<property name="address" value="Bangalore"></property>
</bean>
<bean class="org.springframework.beans.factoty.annotation.AutowiredAnnotationBeanPostProcessor"></bean>
</beans>

Now it would produce the same output as before.

What happens here is, @Autowired annotation first looks for the type. If it finds only one bean of the required type, even though the name is different, it will auto-wire.

If there are multiple beans of the required type, what @Autowired annotation does is, as a second step, it will look for the name. If there a bean with same name as that of member variable, it will auto-wire it.

Now suppose that I cannot change the name of the bean, may be because it is referred in some other beans. The other option is to use @Qualifier. Now look at the below code.

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
package com.j2eereference.spring;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
 
public class HDFC implements Bank{
private Branch branch;
 
 
public Branch getBranch() {
return branch;
}
@Autowired
@Qualifier("hdfcRelated")
public void setBranch(Branch branch) {
this.branch = branch;
}
 
@Override
public void getBranchInfo()
{
System.out.println("HDFC Branch code : "+branch.getCode()+"and Address : "+branch.getAddress() );
}
}

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
27
<?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="bank" class="com.j2eereference.spring.HDFC" >
</bean>
<bean id="branchA" class="com.j2eereference.spring.Branch" >
<qualifier value="hdfcRelated"></qualifier>
<property name="code" value="1234"></property>
<property name="address" value="Bangalore"></property>
</bean>
<bean id="branchB" class="com.j2eereference.spring.Branch" >
<property name="code" value="1234"></property>
<property name="address" value="Bangalore"></property>
</bean>
<bean id="branchC" class="com.j2eereference.spring.Branch" >
<property name="code" value="1234"></property>
<property name="address" value="Bangalore"></property>
</bean>
<bean class="org.springframework.beans.factoty.annotation.AutowiredAnnotationBeanPostProcessor"></bean>
</beans>

Now run the application with these changes. It would produce the same output as before.

What happens here is, Spring will check for @Autowired. It will look at the beans for the matching type. Since there multiple beans of the same type, it will look for the matching name. But there is no such bean in this case. Next it will look for the Qualifier. If any of the beans have the qualifier that matches with the qualifier of the member variable to be auto-wired. It finds that there is only bean which matches the qualifier ‘hdfcRelated’ and wires the dependency.

Filed Under: Spring

Constructor injection in spring

June 3, 2015 By j2eereference Leave a Comment

Constructor injection in spring:

In Spring, the dependency injection can be done in two ways – Setter Injection and Constructor Injection.

<property> tag is used to the value of a member  variable. This property tag uses a setter method to initialize the value of a member variable. This is called setter injection.

If the class has a constructor that takes in the parameters for its member variables we use that constructor, instead of a setter, to initialize member variables. To implement this, we use constructor-arg tag.

Consider, we have a class Employee.java which has a  member variable ‘Name’ of type String. (Note that the setName(String name ) is commented)

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 Employee {
 
private String name;
 
public Employee(String name) {
this.name = name;
}
 
 
public String getName() {
return name;
}
 
public void printInfo()
{
System.out.println("Name of the employee:"+getName());
}
}

spring.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
<?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="employee" class="com.j2eereference.spring.Employee" >
<constructor-arg value="XYZ"/>
</bean>
</beans>

Here, the value ‘XYZ’ is sent as a constructor argument when Employee object is initialized and it sets the value of ‘Name’ as XYZ. By using the ‘constructor-arg’, we tell Spring to inject the dependency using a constructor. Note that, unlike property tag, constructor-arg doesn’t have ‘name’ attribute.

Lets test it by calling’employee’ bean.

InfoApp.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 InfoApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
Employee emp = (Employee)context.getBean("employee");
emp.printInfo();
}
}

Output : Name of the employee:XYZ

We can have as many constructors as we want.

Suppose there is another member variable ‘age’ of type int. We can have one more constructor which takes in a String and an int as parameters.

Employee.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
29
package com.j2eereference.spring;
 
public class Employee {
 
private String Name;
private int Age;
public Employee(String name) {
Name = name;
}
public Employee(String name, int age) {
Name = name;
Age = age;
}
 
public int getAge() {
return Age;
}
 
public String getName() {
return Name;
}
public void printInfo()
{
System.out.println("Name of the employee:"+getName()+"and age is:"+getAge());
}
}

And the spring.xml will look like

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"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
               http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
<bean id="employee" class="com.j2eereference.spring.Employee" >
<constructor-arg value="XYZ"/>
<constructor-arg value="20" />
</bean>
</beans>

Output : Name of the employee:XYZ and the age is:20

Here, though there are two constructors, Spring internally identifies the constructor that accepts two parameters and sets the values.Note that the values ‘XYZ’ and ’20’ are defined inside double quotes i.e., they are String type. But Spring takes care of converting the String value of age “20” to int value and then do the assignment.

But this could lead to a potential problem with constructor over-loading. Because the constructor to be called is decided at run-time depending on the constructor parameters. Suppose there is one more constructor which accepts a parameter of type int and sets the ‘Age’. And the bean configuration also has one constructor-arg. Since both int and String constructor parameters are represented in the same fashion and there is no way for Spring to know which constructor to call – whether  to set Name or Age. To resolve this problem, we need to provide the information about the data type. We do this defining the ‘type’ property in the constructor-arg.

Here is how we set the type in the constructor-arg

1
2
3
4
<bean id="employee" class="com.j2eereference.spring.Employee" >
<constructor-arg type="java.lang.String" value="XYZ"/>
<constructor-arg type="int" value="20" />
</bean>

Another way is by specifying the index. We can use index when have to resolve between multiple constructors depending on the order of the parameters. Here is how we specify the index

1
2
3
4
<bean id="employee" class="com.j2eereference.spring.Employee" >
<constructor-arg index="0" value="XYZ"/>
<constructor-arg index="1" value="20" />
</bean>

What happens here is, it first looks for the constructor with two parameters. The first argument is set to value with index=0 and the second argument is set to a value with index=1

 

Filed Under: Spring

Bean autowiring

June 3, 2015 By j2eereference 1 Comment

Bean autowiring :

Auto-wiring is a feature which helps us skip some of the configurations that we have to do by internally injecting the object dependency. It uses setter or construction injection to do it.

Consider the example below. Class Triangle has a property which is a list of objects of type Point.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.j2eereference.spring;
 
import java.util.ArrayList;
import java.util.List;
 
public class Triangle {
List<Point> points = new ArrayList<Point>();
public void draw()
{
for(Point point:points)
{
System.out.println("Point = ("+point.getX()+","+point.getY()+")");
}
}
}

The bean configuration for this would be:

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
<?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="triangle" class="com.j2eereference.spring.Triangle">
<property name="points">
<list>
<ref bean="zeroPoint" />
<ref bean="point1" />
<ref bean="point2" />
</list>
</property>
</bean>
<bean id="zeroPoint" class="com.j2eereference.spring.Point">
<property name="X" value="0" />
<property name="Y" value="0" />
</bean>
<bean id="point1" class="com.j2eereference.spring.Point">
<property name="X" value="20" />
<property name="Y" value="0" />
</bean>
<bean id="point2" class="com.j2eereference.spring.Point">
<property name="X" value="0" />
<property name="Y" value="30" />
</bean>
</beans>

Notice that the property “points” is initialized using the reference beans “zeropoint”, “point1” and “point2”. This kind of configurations can be skipped using auto-wiring.

There are 3 types auto-wiring

Autowiring ByName :

When the names of the bean ids match the names of the member variables of the bean which has a dependency , we can auto-wire beans based on name by setting autowire=”byName” .

Triangle.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
29
30
31
32
33
34
35
package com.j2eereference.spring;
 
public class Triangle {
private Point pointA;
private Point pointB;
private Point pointC;
public Point getPointA() {
return pointA;
}
public void setPointA(Point pointA) {
this.pointA = pointA;
}
public Point getPointB() {
return pointB;
}
public void setPointB(Point pointB) {
this.pointB = pointB;
}
public Point getPointC() {
return pointC;
}
public void setPointC(Point pointC) {
this.pointC = pointC;
}
public void draw()
{
System.out.println("PointA = ("+pointA.getX()+","+pointA.getY()+")");
System.out.println("PointB = ("+pointB.getX()+","+pointB.getY()+")");
System.out.println("PointA = ("+pointC.getX()+","+pointC.getY()+")");
}
}

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
27
<?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="triangle" class="com.j2eereference.spring.Triangle" autowire="byName>
</bean>
<bean id="pointA" class="com.j2eereference.spring.Point">
<property name="X" value="0" />
<property name="Y" value="0" />
</bean>
<bean id="pointB" class="com.j2eereference.spring.Point">
<property name="X" value="20" />
<property name="Y" value="0" />
</bean>
<bean id="pointC" class="com.j2eereference.spring.Point">
<property name="X" value="0" />
<property name="Y" value="30" />
</bean>
</beans>

DrawingApp.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.j2eereference.spring;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class DrawingApp {
 
/**
* @param args
*/
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
Triangle triangle = (Triangle)context.getBean("triangle");
triangle.draw();
 
}
 
}

Point.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
29
30
31
package com.j2eereference.spring;
 
public class Point {
 
private int X;
private int Y;
public Point() {
super();
}
public Point(int x, int y) {
super();
X = x;
Y = y;
}
public int getX() {
return X;
}
public void setX(int x) {
X = x;
}
public int getY() {
return Y;
}
public void setY(int y) {
Y = y;
}
}

The member variables pointA, pointB and pointC match the names of the bean ids. Since the autowire is set to “byName” for the bean triangle, it internally references the bean ids pointA, PointB and pointC for the member variables.

Output:
PointA = (0,0)
PointB = (20,0)
PointC = (0,30)

Autowiring ByType :

This is achieved by setting autowire=”byType”. It works if the type of the of the member variables are unique. In this case, if the type of the member variable matches the class of the bean, then it is auto-wired by type. The limitation here is if there are more than one member variables of same type it wont work. Considering the above example, Triangle.java has 3 member variables of type Point.  Hence auto-wring by type wont work in this case.

Autowiring ByConstructor :

It works same as auto-wire by name, but does constructor injection instead of setter injection by setting autowire=”constructor”. Suppose there is a class that has 3 member variables, each of different type and there is a constructor that accepts 3 parameters. There needs to be 3 beans configured for each type of member variables and autowire=”constructor”. Spring checks the type of the constructor arguments and matches with the beans defined for auto-wiring.

By default, auto-wire is off. We have to explicitly set this tag to use this feature.

Though auto wiring feature may look cool, it is difficult to debug in real world application where there are lot of beans and references if it is all auto-wired. Hence auto-wiring may be recommended for small application whereas explicit wiring is recommended for large applications.

Filed Under: Spring

LifeCycle call backs in Spring

May 21, 2015 By j2eereference 1 Comment

LifeCycle callback in spring – 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 .

Lets see how the lifecycle call back works in Spring with the below example code.

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
package com.j2eereference.spring;
 
public class Person {
 
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void display(){
System.out.println("Name is  "+name);
System.out.println("Age is  "+age);
}
public void myInit(){
System.out.println("This is from myInit Method");
}
public void myDestroy(){
System.out.println("This is from myDestroy Method");
}
}

Spring.xml

XHTML
1
2
3
4
5
6
7
8
9
10
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">  
     <bean id="personBean" class="com.j2eereference.spring.Person" init-method="myInit" destroy-method="myDestroy">
    <property name="name" value="Leo"/>
    <property name="age" value="30"/>
    </bean>    
</beans>

Now lets test this configuration with the below code:

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

context.registerShutdownHook(); – This is required only in case of desktop application, the ShutdownHook is called when main method exit.
If you have a web application you don’t have to do this, rather Spring context will know when to end.

Output:

This is from myInit Method
Name is Leo
Age is 30
This is from myDestroy Method

Here you can notice that the myInit  method is getting called before executing the display method and myDestroy method is getting called at the end.

If you have scenario where in you want to call the same init and destroy method for all the defined beans . We can set it as default-init-method and default-destroy-method as below.

 

XHTML
1
2
3
4
5
6
7
8
9
10
11
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd" <strong>default-init-method</strong>="myInit" <strong>default-destroy-method</strong>="myDestroy">
  
     <bean id="personBean" class="com.j2eereference.spring.Person">
    <property name="name" value="Leo"/>
    <property name="age" value="30"/>
    </bean>    
</beans>

 

Filed Under: Spring

BeanPostProcessor in Spring

May 19, 2015 By j2eereference Leave a Comment

BeanPostProcessor in Spring

As the name indicate, BeanPostProcessor are classes that tells spring to do some action while initializing the bean.  The BeanPostProcessor interface defines callback methods that you can implement to  process fields that were set, perform validation on a bean etc. You can also implement some custom logic after the Spring container finishes instantiating.

BeanPostProcessor interface has two methods.

  • public Object postProcessAfterInitialization(Object arg0, String arg1)

postProcessAfterInitialization method accept two parameters , First is the bean object and second is the Bean Name .This method returns the Bean object

  •  public Object postProcessBeforeInitialization(Object arg0, String arg1)

postProcessBeforeInitialization method accept two parameters , First is the bean object and second is the Bean Name .This method returns the Bean object

Here in this article lets see how to configure the BeanPostProcessor with an example . Lets create a person class which has two member variables name ,age and a method display() to print the name and age values

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.j2eereference.spring;
 
public class Person {
 
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void display(){
System.out.println("Name is  "+name);
System.out.println("Age is  "+age);
}
}

Spring.xml :

 

XHTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans.xsd">
 
    <bean id="personBean1" class="com.j2eereference.spring.Person">
    <property name="name" value="George"/>
    <property name="age" value="30"/>
    </bean>
    
    <bean id="personBean2" class="com.j2eereference.spring.Person">
    <property name="name" value="Leo"/>
    <property name="age" value="25"/>
    </bean>
    <bean class="com.j2eereference.spring.DisplayNameBeanPostProcessor">
    </bean>
</beans>

Here you can notice that we have added a bean ,com.j2eereference.spring.DisplayNameBeanPostProcessor .

Now lets create the class DisplayNameBeanPostProcessor

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.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
 
public class DisplayNameBeanPostProcessor implements BeanPostProcessor{
 
@Override
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
System.out.println("This is After Initilizing bean "+beanName);
return bean;
}
 
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
System.out.println("This is before Initializing bean "+beanName);
return bean;
}
 
}

In this class we have to impement BeanPostProcessor . I have implemented postProcessAfterInitialization and postProcessBeforeInitialization methods to print the respective messages with bean name .

Now lets test this configuration with the below code

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 SpringDemo {
public static void main(String[] args) {
ApplicationContext context= new ClassPathXmlApplicationContext("spring.xml");
Person person= (Person)context.getBean("personBean1");
person.display();
}
}

Output

May 19, 2015 4:33:43 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@71c2812: startup date [Tue May 19 16:33:43 IST 2015]; root of context hierarchy
May 19, 2015 4:33:43 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]

This is before Initializing bean personBean1
This is After Initilizing bean personBean1
This is before Initializing bean personBean2
This is After Initilizing bean personBean2
Name is  Leo
Age is 25

 

  • postProcessAfterInitialization and postProcessBeforeInitialization methods are getting called while spring initialize the beans.
  • postProcessAfterInitialization and postProcessBeforeInitialization methods are getting called for each and every bean configured in the spring.xml
  • You can have any number of BeanPostProcessor.

 

 

Filed Under: Spring

Initializing list of values using Spring

May 14, 2015 By j2eereference Leave a Comment

Initializing list of values using Spring

There can be a situation where we need to initialize a list of objects while loading the class.

In this article we will see how spring supports the collection objects. Let’s take an example of Line object . Here we have one start point location ,one  end point location, and  each of these has X and Y values  eg:  start(X,Y) and  end(X,Y).

Spring has List , Map  and  Set interfaces to support for injecting the dependency of list of objects

In this example we can see how to configure the dependency of list of objects.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.j2eereference.spring;
import java.util.List;
 
public class Line {
private List points;
 
public List getPoints() {
return points;
}
public void setPoints(List points) {
this.points = points;
}
public void displayLinePoints()
{
for(Point point:points){
System.out.println("point is ("+point.getValueX()+","+point.getValueY()+")");
 
}
}
}

In the above example code we have declared the member variable points as list, which is nothing but a list of Point objects.. We have the Point class as below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.j2eereference.spring;
public class Point {
 
private int valueX;
private int valueY;
public int getValueX() {
return valueX;
}
public void setValueX(int valueX) {
this.valueX = valueX;
}
public int getValueY() {
return valueY;
}
public void setValueY(int valueY) {
this.valueY = valueY;
}
}

Now We will see how to configure initializing the list values in 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
<?xml version="1.0" encoding="UTF-8" ?>
 
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
 
  <bean id="LineBean" class="com.j2eereference.spring.Line">
    <property name="points">
       <list>
         <ref bean="startPoint"/>
         <ref bean="endPoint"/>
        </list>
     </property>
  </bean>
 
  <bean id="startPoint" class="com.j2eereference.spring.Point">
    <property name="valueX" value="10"/>
    <property name="valueY" value="20"/>
  </bean>
 
  <bean id="endPoint" class="com.j2eereference.spring.Point">
    <property name="valueX" value="20"/>
    <property name="valueY" value="30"/>
  </bean>
</beans>

Let’s run the below code to print the value of list objects which are configured in the spring.xml file.

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 SpringDemo {
public static void main(String[] args) {
ApplicationContext context= new ClassPathXmlApplicationContext("spring.xml");
Line line= (Line)context.getBean("LineBean");
line.displayLinePoints();
}
}

output

12 May, 2015 12:50:08 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@16fd0b7: startup date [Tue May 12 00:50:08 IST 2015]; root of context hierarchy
12 May, 2015 12:50:08 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]

point is (10,20)
point is (20,30)

Filed Under: Spring

  • « Previous Page
  • Page 1
  • Page 2
  • Page 3
  • 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

  • Java Buzzwords
  • Anonymous Inner Class in Java
  • Network Programming – java.net Package
  • Java Regular Expressions
  • Method Local Inner Class in Java
  • URL Processing in Java
  • Iterator Design Pattern Implementation using Java
  • Strategy Design Pattern Implementation using Java
  • Decorator Design Pattern
  • Adapter Design Pattern Implementation using Java
  • JSF Composite Components
  • JSF UI Components
  • What is JavaServer Faces (JSF)?
  • GOF Design Patterns
  • History and Need for Design Patterns

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.