Concept of AOP (Aspect oriented programming) every spring programmer use without knowing about it .

Many of spring programmer these days, when it’s comes to AOP (Aspect oriented programming) says heard about it but never used it . It’s interesting to see that many of them use it without knowing about it . One of the example that most of us used is spring declarative transaction management annotation. We do know what @transactional annotation does but we do not know and doesn’t even care about how it is doing it ? Spring is using AOP here .

Let’s understand how AOP actually works . Well in theory when one bean(java object) call method of another bean then spring create a proxy between them . If there is an interface for that bean and coding is on that interface than it will work as proxy otherwise spring will create a proxy for it . This proxy can be programmed through AOP and we can code if we want to do something before method call,after method call,after exception throw etc .

Now let’s see how this theory works in actual . Let’s create one custom annotation like @transactional to understand it better .

Step 1 : To work AOP with spring we need to define


in custom-config.xml .

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""        xmlns:xsi=""        xmlns:context=""        xmlns:aop=""        xmlns:mvc=""        xsi:schemaLocation="          ">

  <!-- Scans for application @Components to deploy -->
  <context:component-scan base-package="com.stevenlanders.*" />

  <!-- enable AOP -->


Step 2 : Create you custom annotation .

public @interface LogDuration {
   String value();

Step 3 : Write your AOP class. To do it, You need to use @Aspect annotation on that class . Then you need to create advice in this class. To do so, You need to choose one of the annotation given below .
@Before – Run before the method execution
@After – Run after the method returned a result
@AfterReturning – Run after the method returned a result, intercept the returned result as well.
@AfterThrowing – Run after the method throws an exception
@Around – Run around the method execution, combine all three advices above.
We are going to choose @Around here as we need to start and stop timer before and after of this method execution .

public class AopExample{

    //for any method with @LogDuration, no matter what the return type, name, or arguments are, call this method
    @Around("execution(@com.stevenlanders.annotation.LogDuration * *(..)) && @annotation(logDurationAnnotation)")
    public Object logDuration(ProceedingJoinPoint joinPoint, LogDuration logDurationAnnotation) throws Throwable {

        //capture the start time
        long startTime = System.currentTimeMillis();

        //execute the method and get the result
        Object result = joinPoint.proceed();

        //capture the end time
        long endTime = System.currentTimeMillis();

        //calculate the duration and print results
        long duration = endTime - startTime;
        System.out.println(logDurationAnnotation.value()+": "+duration+"ms"); //you should use a logger  

        //return the result to the caller
        return result;


Step 4 : Put your annotation on methods for which you want to print execution time .

public class ExampleController{

     @LogDuration("Hello World API")
     public @ResponseBody String getHelloWorld(){
          try {
          } catch (InterruptedException e) {
            throw new RuntimeException("Sleep Interrupted", e);
          return "Hello World";


Step 5 : Run this code .

Hello World API: 3002ms

For more information, see the Spring AOP Documentation

Other related posts are :
Interview questions on concept of code on interface rather then class
JPA Hibernate Sequence generator generating odd ID value and IntegrityConstraintVolation exception is coming
Top 10 spring interview questions and their answers. Spring basic concepts.
Logback logs are not working. Log4j logs are not working. Steps to make logging work.

Please share this posts on Facebook,Linkeedin,Google+,Twitter by clicking on below icons.


Top 10 spring interview questions and their answers. Spring basic concepts.

Spring framework is the most recognized framework in java right now . So if you are thinking about changing job in java profile spring framework knowledge is must . Spring IOC and spring-mvc are two hot topics of any interviewer in java these days .The basic categorisation any interviewer will do in front of any interviewee will be :

  1. spring IOC
  2. Dependency Injection
  3. spring security
  4. spring mvc
  5. spring AOP


some less recognized topics also like spring jdbc , spring  JMS but they can be only ask by person who seriously worked on them.  Let’s start with spring IOC and dependency injection first.

Top10  spring interview questions and their answers

Question 1 : What is Dependency Injection

Answer :  Mostly every interviewer start interview this question of spring if he requires spring knowledge in a candidate. As it is explained by name when you injecting dependency of one  java object into another java object that is called dependency injection. Then interviewer  will ask Do I need spring framework for dependency injection then answer is  No.  We were doing it since java started with association of one java object into another that is also dependency injection . Then why do, I need spring for dependency injection. We do not need spring framework for dependency injection we need it for Inversion of control . Means without spring we need to initialize our associated class(injected) class with new   keyword of java but with spring framework is doing this for us. Now he will think that you know basic fundamental of spring at least.

Question 2 : What is Inversion of control as you mentioned in your answer and how spring is defining object for us without using new keyword.

Answer :  Now you will say that spring took control in his hand of creating object and that is called inversion of control. Second how spring is doing it . Spring took definition in xml or in annotation from us that at runtime which object is need to be injected in which one at runtime and create that object using reflection at time of container loading.

Question 3 : What is the benefit I got using spring , I could used new keyword what is the issue with that.

Answer :  Now you will explain it by writing a code below.

You will say if I have an interface called PET .

Interface Pet{}

Now I have an implementation class Dog having name as “pet” (In annotation or XML where bean is defined ) for this Pet interface.

@Named("pet")Class Dog{}

Now I have one object called Manav and this manav has a pet as dog.

Class Manav{
private Pet pet;

Now spring will define Dog object for Pet interface at runtime. But if we were using new keyword we have to define pet  = new Dog(); inside manav and in future manav does not need Dog he need Cat now then we have to replace Dog with Cat in code everywhere but with help of spring  we will remove @named(“pet”) from Dog class and put it at Cat class like below.

Class Cat{}

and spring will initialized Pet which Manav have with cat implementation without changing any code. Now he will be satisfied that you know why we are using spring IOC.

Question 4 : What are different type of IOC.

Answer :  Two types of IOC are present in spring.

  1. Constructor Based : When container called constructor with number of arguments and use that constructor to set associated objects  value with help of those arguments.
  2. Setter Based : Setter based DI happened when container call different setter methods of associated objects to initialize those objects if a non augmented constructor found in that bean.
  3. Field Injection : Field injection happen when we define @inject on field and does not want to define it’s setter and getter . Then spring container assign value to these fields directly through reflection without calling any method.


Question 5 : What are different stages of a bean(Life of a bean).

Answer :  Below steps are followed.

  1. Container will look bean definition in xml or annotations and initialize that bean through reflection.
  2. If an augmented constructor is found then it will call that constructor based on arguments given in beans.xml or else call their setter methods that is also based on beans.xml .
  3. If somebody used annotation then container will look out for annotated associated objects in that bean and initialize them according to their implementations.
  4. If a BeanPostProcessor is attached with that bean then container will call overridden processBeforeInitialization() method .If an init() method is specified then it will call. If a method with nay name but having @postprocessor annotation is present then it will be called.
  5. Now bean will be in container until container will feel that there is no live reference using this bean and let java garbage collector collect this bean.
  6. If bean has implemented DisposableBean interface then destroy method will be called before this bean will be destroyed. If a method with any name but having @predestroy annotation is present then it will be called.


Question 6 : Difference between BeanFactory and ApplicationContext.

Answer :

A BeanFactory is like a factory class that separate beans configurations ,their dependency from actual code and instantiates the bean whenever needed. XMLBeanFactory is one of the implementation of Beanactory which takes xml file as configuration data and instantiate beans according to that XML file.

BeanFactory factory = new XmlBeanFactory(new FileInputStream("beans.xml"));

ApplicationContext is same like BeanFactory except it have some more features like. It supports multiple files as config XML. It supports bean life cycle events. It supports internationalization etc.

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/application-context.xml");

ApplicationContext is preferred way to use spring but if project require only basic functionality of spring then BeanFactory can also be used.

Question 7 : Why beans are singleton in spring. Does it make them thread unsafe.

Answer :  Beans are singleton in spring . Well if we are using beans as functionality exposures( Means services who are exposing their methods) then it will not be thread safe but if we are using beans as data carriers and trying to modifying or performing some operation on that data then it is not thread safe. For that kind of functionality we should use prototype bean or commonpool functionality of spring.

Question 8 : In how many ways, we can provide configuration data to Spring.

Answer :  We can provide configuration data in three ways to spring framework so that spring can instantiate and inject beans into each other when required.

  1. XML based configuration(Beans.xml)
  2. Annotation based configuration(@autowired/@resources etc.)
  3. Java based configuration(@inject,@named)

Question 9 : What is XML based configuration and it’s example.

Answer :  In spring we can configure beans definition and their dependency on each other in XML files and register those files with help of BeanFactory or ApplicationContext while making application up as I explained above.

<beans xmlns=""    xmlns:xsi=""    xsi:schemaLocation="">    <!-- A simple bean definition -->   <bean id="..." class="...">       <!-- collaborators and configuration for this bean go here -->   </bean></beans>

Question 10 : What is Annotation and Java based configuration and it’s example.

Answer :  In spring we can configure beans definition and their dependency on each other in java source code with help of annotations. These annotations are of two types .

  1. Spring Based : These annotations are given by spring and present in spring framework jars .They can only be used when spring framework is present in application. These annotations majorly are
    @component(To define  a unique name for bean)
    @autowwired(To autowire bean into another bean)
    @resource(To define implementation of this bean which need to bean injected at object creation it match this with @component).
  2. Java Based : These are given by java and can be used with any inversion of control framework. Noo dependency on spring. These annotations majorly are
    @named(To define unique name)
    @inject(To inject bean into another).

Other related posts are :
String interview questions and answers
String vs StringBuffer vs StringBuilder
JPA Hibernate Sequence generator generating odd ID value and IntegrityConstraintVolation exception is coming
Logback logs are not working. Log4j logs are not working. Steps to make logging work.

Please share these posts on facebook,Linkeedin,Google+,Twitter by clicking on below icons.

Set datasource spring bean properties dynamically if server is not available

Hi Readers today i want to share with you guys something that i faced recently.

Problem :

Recently i was developing a spring application in which container need to initialized by public static void main method rather then any server .
We want user to enter details with swing ui and do not want to save them in properties file at run time. Risk in this is, that anybody can look into properties file which is a security threat.
So now the question is that how we will tell spring container to which DataBase it needs to connect with.

Solution :

So to solve this problem, I created a class which extends BasicDatasource as code given below.

public class CustomDatasource extends BasicDatasource {

private static String hostName;
private static String dbName;
private static String port;
private static String userName;
private static String dbPassword;

private CustomDatasource(){

public static String getHostName() {
return hostName;

public static void setHostName(String hostName) {
CustomDatasource.hostName = hostName;

public static String getDbName() {
return dbName;

public static void setDbName(String dbName) {
CustomDatasource.dbName = dbName;

public static String getPort() {
return port;

public static void setPort(String port) {
CustomDatasource.port = port;

public static String getUserName() {
return userName;

public static void setUserName(String userName) {
CustomDatasource.userName = userName;

public static String getDbPassword() {
return dbPassword;

public static void setDbPassword(String dbPassword) {
CustomDatasource.dbPassword = dbPassword;

Now make this class as datasource bean in Beans.xml and inject this bean into persistanceUnitManager .
Now initialize spring container as given below.

public class Test {
public static void main(String args[]){
Scanner in = new Scanner(;
System.out.println("Enter a string");
String dbName = in.nextLine();
String hostName = in.nextLine();
String port = in.nextLine();
String userName = in.nextLine();
String dbPassword = in.nextLine();
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/Beans.xml");

Now without saving database configuration in any properties file your application will be able to connect with database.

Other related posts are :
HTML to PDF conversion in JAVA | HTML to PDF example in JAVA
Top 10 spring interview questions and their answers. Spring basic concepts.
MQ connection not closed and giving MQ Error-2009
JPA Hibernate Sequence generator generating odd ID value and IntegrityConstraintVolation exception is coming

Please share this posts on facebook,Linkeedin,Google+,Twitter by clicking on below icons.