Showing posts with label spring. Show all posts
Showing posts with label spring. Show all posts

Saturday 31 August 2013

Top Most Spring Interview Questions 2


11) What is the difference between Bean Factory and Application Context ?  

On the surface, an application context is same as a bean factory. But application context offers much more..
  • Application contexts provide a means for resolving text messages, including support for i18n of those messages.
  • Application contexts provide a generic way to load file resources, such as images.
  • Application contexts can publish events to beans that are registered as listeners.
  • Certain operations on the container or beans in the container, which have to be handled in a programmatic fashion with a bean factory, can be handled declaratively in an application context.
  • ResourceLoader support: Spring’s Resource interface us a flexible generic abstraction for handling low-level resources. An application context itself is a ResourceLoader, Hence provides an application with access to deployment-specific Resource instances.
MessageSource support: The application context implements MessageSource, an interface used to obtain localized messages, with the actual implementation being pluggable.
12) What is AOP module?
The AOP module is used for developing aspects for our Spring-enabled application. Much of the support has been provided by the AOP Alliance in order to ensure the interoperability between Spring and other AOP frameworks. This module also introduces metadata programming to Spring. Using Spring’s metadata support, we will be able to addannotations to our source code that instruct Spring on where and how to apply aspects.
13) What is JDBC abstraction and DAO module?
Using this module we can keep up the database code clean and simple, and prevent problems that result from a failure to close database resources. A new layer of meaningful exceptions on top of the error messages given by several database servers is bought in this module. In addition, this module uses Spring’s AOP module to provide transaction management services for objects in a Spring application.
14) What are object/relational mapping integration module?
Spring also supports for using of an object/relational mapping (ORM) tool over straight JDBC by providing the ORM module. Spring provide support to tie into several popular ORM frameworks, including Hibernate, JDO, and iBATIS SQL Maps. Spring’s transaction management supports each of these ORM frameworks as well as JDBC.
15)What is web module?
This module is built on the application context module, providing a context that is appropriate for web-based applications. This module also contains support for several web-oriented tasks such as transparently handling multipart requests for file uploads and programmatic binding of request parameters to your business objects. It also contains integration support with Jakarta Struts.

Or

Spring comes with a full-featured MVC framework for building web applications. Although Spring can easily be integrated with other MVC frameworks, such as Struts, Spring’s MVC framework uses IoC to provide for a clean separation of controller logic from business objects. It also allows you to declaratively bind request parameters to your business objects. It also can take advantage of any of Spring’s other services, such as I18N messaging and validation.
16) What is a BeanFactory?
A BeanFactory is an implementation of the factory pattern that applies Inversion of Control to separate the application’s configuration and dependencies from the actual application code.
17) What is AOP Alliance?
AOP Alliance is an open-source project whose goal is to promote adoption of AOP and interoperability among different AOP implementations by defining a common set of interfaces and components.
18) What is Spring configuration file?
Spring configuration file is an XML file. This file contains the classes information and describes how these classes are configured and introduced to each other.
19) What does a simple spring application contain?
These applications are like any Java application. They are made up of several classes, each performing a specific purpose within the application. But these classes are configured and introduced to each other through an XML file. This XML file describes how to configure the classes, known as the Spring configuration file.
20) What is XMLBeanFactory?
BeanFactory has many implementations in Spring. But one of the most useful one isorg.springframework.beans.factory.xml.XmlBeanFactory, which loads its beans based on the definitions contained in an XML file. To create an XmlBeanFactory, pass a java.io.InputStream to the constructor. TheInputStream will provide the XML to the factory. For example, the following code snippet uses a java.io.FileInputStream to provide a bean definition XML file to XmlBeanFactory.
 
        BeanFactory factory = new XmlBeanFactory(new FileInputStream("beans.xml"));
To retrieve the bean from a BeanFactory, call the getBean() method by passing the name of the bean you want to retrieve.
 
        MyBean myBean = (MyBean) factory.getBean("myBean");


Keywords: Spring Faq's

Top Most Spring Interview Questions1


1) What is Spring?


Spring is a lightweight inversion of control and aspect-oriented container framework.

2)Explain Spring?

  • Lightweight : Spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 1MB. And the processing overhead is also very negligible.
  • Inversion of control (IoC) : Loose coupling is achieved in spring using the technique Inversion of Control. The objects give their dependencies instead of creating or looking for dependent objects.
  • Aspect oriented (AOP) : Spring supports Aspect oriented programming and enables cohesive development by separating application business logic from system services.
  • Container : Spring contains and manages the life cycle and configuration of application objects.
  • Framework : Spring provides most of the intra functionality leaving rest of the coding to the developer.

3) What are the advantages of Spring framework?

  • The advantages of Spring are as follows:
  • Spring has layered architecture. Use what you need and leave you don't need now.
  • Spring Enables POJO Programming. There is no behind the scene magic here. POJO programming enables continuous integration and testability.
  • Dependency Injection and Inversion of Control Simplifies JDBC
  • Open source and no vendor lock-in.

4) What is the structure of Spring framework?



5) What are the different modules in Spring framework?


  • The Core container module
  • Application context module
  • AOP module (Aspect Oriented Programming)
  • JDBC abstraction and DAO module
  • O/R mapping integration module (Object/Relational)
  • Web module
  • MVC framework module

6) What is IOC (or Dependency Injection)? 


The basic concept of the Inversion of Control pattern (also known as dependency injection) is that you do not create your objects but describe how they should be created. You don't directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up.

i.e., Applying IoC, objects are given their dependencies at creation time by some external entity that coordinates each object in the system. That is, dependencies are injected into objects. So, IoC means an inversion of responsibility with regard to how an object obtains references to collaborating objects.



7) What are the different types of IOC (dependency injection) ? 
      
     There are three types of dependency injection:
Constructor Injection (e.g. Pico container, Spring etc): Dependencies are provided as constructor parameters.
Setter Injection (e.g. Spring): Dependencies are assigned through JavaBeans properties (ex: setter methods).
Interface Injection (e.g. Avalon): Injection is done through an interface.
Note: Spring supports only Constructor and Setter Injection

8) What are the benefits of IOC (Dependency Injection)?

 

Benefits of IOC (Dependency Injection) are as follows:
Minimizes the amount of code in your application. With IOC containers you do not care about how services are created and how you get references to the ones you need. You can also easily add additional services by adding a new constructor or a setter method with little or no extra configuration.
Make your application more testable by not requiring any singletons or JNDI lookup mechanisms in your unit test cases. IOC containers make unit testing and switching implementations very easy by manually allowing you to inject your own objects into the object under test.
Loose coupling is promoted with minimal effort and least intrusive mechanism. The factory design pattern is more intrusive because components or services need to be requested explicitly whereas in IOC the dependency is injected into requesting piece of code. Also some containers promote the design to interfaces not to implementations design concept by encouraging managed objects to implement a well-defined service interface of your own.
IOC containers support eager instantiation and lazy loading of services. Containers also provide support for instantiation of managed objects, cyclical dependencies, life cycles management, and dependency resolution between managed objects etc.

9) What is the Core container module?


This module is provides the fundamental functionality of the spring framework. In this module BeanFactory is the heart of any spring-based application. The entire framework was built on the top of this module. This module makes the Spring container.

10) What is Application context module?


The Application context module makes spring a framework. This module extends the concept of BeanFactory, providing support for internationalization (I18N) messages, application lifecycle events, and validation. This module also supplies many enterprise services such JNDI access, EJB integration, remoting, and scheduling. It also provides support to other framework.


Thursday 29 August 2013

Top Most Top 10 Spring Interview Questions Answers J2EE

Spring framework interview questions is in rise on J2EE and core Java interviews,  As Spring is the best framework available for Java application development and now Spring IOC container and Spring MVC framework are used as de-facto framework for all new Java development. With this popularity interview questions from spring framework is top on any list of  core Java Interview questions. I thought to put together some spring interview questions and answers which has appeared on many Java and J2EE interviews and useful for practicing before appearing on any Java Job interview. This list of Spring interview questions and answers contains questions from Spring fundamentals e.g. Spring IOC and dependency Injection, Spring MVC framework, Spring Security, Spring AOP etc, because of length of this post I haven't included Spring interview questions from Spring JDBC and JMS which is also a popular topic in core Java and J2EE interviews. I suggest to prepare those as well. Any way these Spring questions are not very difficult and based on fundamentals e.g. What is default scope of Spring bean and mostly asked during first round or telephonic round of Java interview. Although you can find answers of these Spring interview questions by doing Google but I have also included some answers for quick reference. As I said Spring  and Spring MVC is fantastic Java framework and if you are not using it than start using it, these questions will give you some head start as well.
Read more »

Monday 26 August 2013

Top Most Spring - java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener Quick Solution

If you have worked in Spring MVC than you may be familiar with  
java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
which is common problem during deployment. Spring MVC throws  java.lang.ClassNotFoundException:                           org.springframework.web.context.ContextLoaderListener ,
when its not able to find org.springframework.web.context.ContextLoaderListener class which is used to load spring MVC configuration files like application-context.xml and other Spring Framework configuration files defined in context-param element of web.xmlin an Spring MVC web application as:
Read more »

Friday 23 August 2013

Top Most How to Convert Collection to String in Java - Spring Framework Example

How to convert Collection to String in Java
Many times we need to convert any Collection like Set or List into String like comma separated or any other delimiter delimited String. Though this is quite a trivial job for a Java programmer as you just need to Iterate through loop and create a big String where individual String are separated by delimiter, you still need to handle cases like last element should not have delimiter or at bare minimum you need to test that code. I like Joshua Bloach advise on Effective Java to use libraries for those common task let it be internal proprietary library or any open source library as used in previous examples of  Spring, Apache Commons or Google’s Guava but point is that you should avoid converting ArrayList to String like common task by yourself on application code.
Read more »

Top Most What is difference between BeanFactory and ApplicationContext in Spring framework

BeanFactory vs ApplicationContext
Difference between BeanFactory and ApplicationContext in Spring framework is a another frequently asked Spring interview question mostly asked to Java programmers with 2 to 4 years experience in Java and Spring. Both BeanFactory and ApplicationContext provides way to get bean from Spring IOC container by calling getBean("bean name"), but there are some difference in there working and features provided by them. One difference between bean factory and application context is that former only instantiate bean when you call getBean() method while ApplicationContext instantiate Singleton bean when container is started,  It doesn't wait for getBean to be called. This interview questions is third in my list of frequently asked spring questions e.g. Setter vs Constructor Injection and  What is default scope of Spring bean. If you are preparing for Java interview and expecting some Spring framework question, It’s worth preparing those questions. If you are new in Spring framework and exploring Spring API and classes than you would like check my post on some Spring utility functions e.g. calculating time difference with StopWatch and  escaping XML special characters using Spring HtmlUtils. Coming back to BeanFactory vs ApplicationContext, let’s see some more difference between them in next section.
Read more »

Thursday 22 August 2013

Top Most Spring Security Example Tutorial - How to limit number of User Session in Java J2EE

Spring security can limit number of session a user can have. If you are developing web application specially secure web application in Java J2EE then you must have come up with requirement similar to online banking portals have e.g. only one session per user at a time or no concurrent session per user. You can also implement this functionality without using spring security but with Spring security its just piece of cake with coffee :). Spring Security provides lots of Out of Box functionality a secure enterprise or web application needed like authentication, authorization, session management, password encoding, secure access, session timeout etc. In our spring security example we have seen how to do LDAP Authentication in Active directory using spring security and in this spring security example we will see how to limit number of session user can have in Java web application or restricting concurrent user session.
Read more »

Top Most What is Bean scope in Spring MVC framework with Example

Bean scope in Spring framework or Spring MVC are scope for a bean managed by Spring IOC container. As we know that Spring is a framework which is based on Dependency Injection and Inversion of Control and provides bean management facilities to Java application. In Spring managed environment bean (Java Classes) are created and wired by Spring framework. Spring allows you to define how those beans will be created and scope of bean is one of those details. This Spring tutorial is next on my earlier post on Spring like how to implement LDAP authentication using Spring security and  How to limit number of user session in web application, if you haven’t read them already you may find them useful.

In spring framework bean declared in ApplicationContext.xml can reside in five scopes:

1) Singleton (default scope)
2) prototype
3) request
4) session
5) global-session
Read more »

Sunday 18 August 2013

Top Most Difference between Setter Injection vs Constructor Injection in Spring framework

Spring Setter vs Constructor Injection
Spring supports two types of dependency Injection, using setter method e.g. setXXX() where XXX is dependency or via constructor argument. First way of dependency injection is known as setter injection while later is known as constructor injection. Both approaches of Injecting dependency on Spring bean has there pros and cons, which we will see in this Spring framework article. Difference between Setter Injection and Constructor Injection in Spring is also a popular Spring framework interview question.Some time interviewer also ask as When do you use Setter Injection over Constructor injection in Spring or simply benefits of using setter vs constructor injection in Spring framework. Points discussed in this article not only help you to understand Setter vs Constructor Injection but also Spring's dependency Injection process. By the way if you are new in Spring framework and exploring Spring API you may find my post on using Spring stopwatch to calculate time difference and Spring’s HtmlUtils to escape HTML special character in Java useful and informative. 
Read more »

Top Most How to setup JNDI Database Connection pool in Tomcat - Spring Tutorial Example

Setting JNDI Database Connection pool in Spring and Tomcat is pretty easy. Tomcat server documentation gives enough information on how to setup connection pool in Tomcat 5, 6 or 7. Here we will use Tomcat 7 along with spring framework for creating connection pool in Tomcat server and accessing them in Spring using JNDI code. In our last article we have seen how to setup database connection pool in Spring for core Java application which doesn't run on web server or application server and doesn't have managed J2EE container. but if you are developing web application than its better to use server managed connection pool and access them using JNDI. Spring configuration will be generic and just based on JNDI name of Datasource so it will work on any J2EE Server e.g. glassfish, WebLogic, JBoss or WebSphere until JNDI name is same. Tomcat is my favorite web server and I use it a lot on development and its comes integrated with IDE like Eclipse and Netbeans. I am using it for all test and development purpose, Though beware with java.lang.OutOfMemoryError: PermGen space in tomcat,
Read more »

Thursday 15 August 2013

Top Most JDBC Database connection pool in Spring Framework – How to Setup Example

Setting up JDBC Database Connection Pool in Spring framework is easy for any Java application, just matter of changing few configuration in spring configuration file.If you are writing core java application and not running on any web or application server like Tomcat or  Weblogic,  Managing Database connection pool using Apache Commons DBCP and Commons Pool along-with Spring framework is nice choice but if you have luxury of having web server and managed J2EE Container, consider using Connection pool managed by J2EE server those are better option in terms of maintenance, flexibility and also help to prevent java.lang.OutofMemroyError:PermGen Space in tomcat by avoiding loading of JDBC driver in web-app class-loader, Also keeping JDBC connection pool information in Server makes it easy to change or include settings for JDBC over SSL. In this article we will see how to setup Database connection pool in spring framework using Apache commons DBCP and commons pool.jar

This article is in continuation of my tutorials on spring framework and database like LDAP Authentication in J2EE with Spring Security and  manage session using Spring security  If you haven’t read those article than you may find them useful.
Read more »

Top Most Inversion of Control and Dependency Injection design pattern with real world Example - Spring tutorial

Inversion of Control and Dependency Injection is a core design pattern of Spring framework. IOC and DI design pattern is also a popular design pattern interview question in Java.As name suggest Inversion of control pattern Inverts responsibility of managing life cycle of object e.g. creating object, setting there dependency etc from application to framework, which makes writing Java application even more easy. Programmer often confused between IOC and DI, well both words used interchangeably in Java world but Inversion of Control is more general concept and Dependency Injection is a concrete design pattern. Spring framework provides two implementation of IOC container in form of Application Context and BeanFactorywhich manages life-cycle of bean used by Java application. As you may know necessity is mother of invention, it benefit to first understand problem solved by IOC and Dependency Injection design pattern. This makes your understanding more clear and concrete. We have touched basics of Dependency Injection and Inversion of control in our article 10 OOPS and SOLID design principles for Java programmer and this Java article tries to explain it by taking a real life example of Service based architecture popular in enterprise Java development. In this Spring or design pattern tutorial we will first see normal implementation of AutditService class, a class in this example which provides auditing in enterprise Java application and than use of dependency Injection. This will  allow us to find out problems and how they are solved by Dependency injection design pattern. . Also there are multiple way to inject dependency in spring e.g. Setter Injection or Constructor Injection, which uses setter method and constructor for injecting dependency, see Setter injection vs Constructor injection  to find out when to use them.
Read more »

Top Most LDAP Active Directory Authentication in Java Spring Security Example Tutorial

LDAP authentication is one of the most popular authentication mechanism around the world for enterprise application and Active directory (an LDAP implementation by Microsoft for Windows) is another widely used ldap server. In many project we need to authenticate against active directory using ldap by credentials provided in login screen. Some time this simple task gets tricky because of various issues faced during implementation and integration and no standard way of doing ldap authentication. Java provides ldap support but in this article I will mostly talk about spring security because its my preferred Java framework for authentication, authorization and security related stuff. you can do same thing in Java by writing your own program for doing LDAP search and than LDAP bind but as I said its much easier and cleaner when you use spring security for LDAP authentication.
Read more »

Monday 5 August 2013

Top Most 5 books to learn Spring framework and Spring MVC for Java Programmers

Spring and Spring MVC is one of the most popular Java framework and most of new Java projects uses Spring these days. Java programmer often ask questions like which books is good to learn Spring MVC or What is the best book to learn Spring framework etc. Actually, there are many books to learn Spring and Spring MVC but only certain books can be considered good because of  there content, examples or the way they explained concept involved in Spring framework. Similar to  Top 5 books on Java programming we will some good books on Spring in this article, which not only help beginners to start with Spring but also teaches some best practices. In order to learn a new technology or a new framework, probably best way is to start looking documentation provided and Spring Framework is no short on this. Spring  provides great, detailed documentation to use various features of Spring framework but despite of that nothing can replace a good book. Luckily both Spring and Spring MVC got couple of good titles which not only explains concepts like Dependency Injection and Inversion of Control which is core to spring framework but also gives coverage to other important aspect of Spring. Following are some of the good books available on Spring and Spring MVC which can help you to learn Spring.
Read more »

Top Most Spring Framework Tutorial - How to call Stored Procedures from Java using IN and OUT parameter example

Spring Framework provides excellent support to call stored procedures from Java application. In fact there are multiple ways to call stored procedure in Spring Framework, e.g. you can use one of the query() method from JdbcTemplate to call stored procedures, or you can extend abstract class StoredProcedure to call stored procedures from Java. In this Java Spring tutorial, we will see second approach to call stored procedure. It's more object oriented, but same time requires more coding. StoredProcedure class allows you to declare IN and OUT parameters and call stored procedure using its various execute() method, which has protected access and can only be called from sub class. I personally prefer to implement StoredProcedure class as Inner class, if its tied up with one of DAO Object, e.g. in this case it nicely fit inside EmployeeDAO. Then you can provide convenient method to wrap stored procedure calls. In order to demonstrate, how to call stored procedures from spring based application, we will first create a simple stored proc using MySQL database, as shown below.
Read more »

Saturday 3 August 2013

Top Most 50 Spring Interview Questions Pdf

Top Most Spring Interview Questions 5

41) What is SQLProvider ?
SQLProvider:
Has one method – getSql()
Typically implemented by PreparedStatementCreator implementers
Useful for debugging.
42)  What is RowCallbackHandler ?
The RowCallbackHandler interface extracts values from each row of a ResultSet.
Has one method – processRow(ResultSet)
Called for each row in ResultSet.
Typically stateful.

43)  What are the differences between EJB and Spring ? Spring and EJB feature comparison.

44)  What is aspect oriented programming (AOP)? Do you have any experience with AOP?
Aspect-Oriented Programming (AOP) complements OOP (Object Oriented Programming) by allowing the
developer to dynamically modify the static OO model to create a system that can grow to meet new requirements.
AOP allows you to dynamically modify your static model consisting mainly of business logic to include the code required to fulfill the secondary requirements or in AOP terminology called cross-cutting concerns (i.e. secondary requirements) like auditing, logging, security, exception handling etc without having to modify the original static model (in fact, we don't even need to have the original code). Better still, we can often keep this additional code in a single location rather than having to scatter it across the existing model, as we would have to if we were using OOP on its own.
For example; A typical Web application will require a servlet to bind the HTTP request to an object and then pass it to the business handler object to be processed and finally return the response back to the user. So only a minimum amount of code is initially required. But once you start adding all the other additional secondary requirements or cross-cutting concerns like logging, auditing, security, exception-handling, transaction demarcation, etc the code will inflate to 2-4 times its original size. This is where AOP can assist by separately modularizing these cross-cutting concerns and integrating theses concerns at runtime or compile time through. aspect weaving. AOP allows rapid development of an evolutionary prototype using OOP by focusing only on the business logic by omitting concerns such as security, auditing, logging etc. Once the prototype is accepted, additional concerns like security, logging, auditing etc can be weaved into the prototype code to transfer it into a production standard application.
AOP nomenclature is different from OOP and can be described as shown below:

Join points: represents the point at which a cross-cutting concern like logging, auditing etc intersects with a main concern like the core business logic. Join points are locations in programs’ execution path like method & constructor call, method & constructor execution, field access, class & object initialization, exception handling execution etc.
pointcut: is a language construct that identifies specific join points within the program. A pointcut defines a collection of join points and also provides a context for the join point.
Advice: is an implementation of a cross-cutting concern which is a piece of code that is executed upon reaching a pointcut within a program.
Aspect: encapsulates join points, pointcuts and advice into a reusable module for the cross-cutting concerns which is equivalent to Java classes for the core concerns in OOP. Classes and aspects are independent of one another. Classes are unaware of the presence of aspects, which is an important AOP concept. Only pointcut declaration binds classes and aspects.
Weaving is the process for interleaving separate cross-cutting concerns such as logging into core concerns such as business logic code to complete the system. AOP weaving composes different implementations of aspects into a cohesive system based on weaving rules. The weaving process (aka injection of aspects into Java classes) can happen at:

Compile-time: Weaving occurs during compilation process.
 Load-time: Weaving occurs at the byte-code level at class loading time.
 Runtime: Similar to load-time where weaving occurs at byte-code level during runtime as join points are
reached in the executing application.

So which approach to use? Load-time and runtime weaving have the advantages of being highly dynamic and
enabling changes on the fly without having to rebuild and redeploy. But Load-time and runtime weaving adversely affect system performance. Compile time weaving offers better performance but requires rebuilding and redeployment to effect changes.

Two of the most interesting modules of the Spring framework are AOP (Aspect Oriented Programming) and Inversion Of Control (IoC) container (aka Dependency Injection). Let us look at a simple AOP example.
STEP 1: Define the interface and the implementation classes. Spring promotes the code to interface design
concept.
public interface Hello {
public void hello();
}
public class HelloImpl implements Hello{
public void hello() {
System.out.println("Printing hello. ");
}
}
STEP 2: Configure the Spring runtime via the SpringConfig.xml file. Beans can be configured and subsequently
injected into the calling Test class.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/springbeans.
dtd">
<beans>
<!-- bean configuration which enables dependency injection -->
<bean id="helloBean" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target">
<bean class="HelloImpl" singleton="false" />
</property>
</bean>
</beans>
STEP 3: Write your Test class. The “SpringConfig.xml” configuration file should be in the classpath.
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext ctx = new FileSystemXmlApplicationContext("SpringConfig.xml");
Hello h = (Hello)ctx.getBean("helloBean");
h.hello();
}
}
If you run the Test class, you should get an output of :
Printing hello.
Now, if you want to trace your methods like hello() before and after in your Hello class, then you can make use of the Spring AOP.
STEP 4: Firstly you need to define the classes for the before and after advice for the method tracing as follows:
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
public class TracingBeforeAdvice implements MethodBeforeAdvice {
public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable {
System.out.println("Just before method call...");
}
import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;
public class TracingAfterAdvice implements AfterReturningAdvice {
public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3)
throws Throwable {
System.out.println("Just after returning from the method call...");
}
}
STEP 5: In order to attach the advice to the appropriate joint points, you must make a few amendments to the
SpringConfig.xml file as shown below in bold:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/springbeans.
dtd">
<beans>
<!-- bean configuration which enables dependency injection -->
<bean id="helloBean"
class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target">
<bean class="HelloImpl" singleton="false" />
</property>
<property name="interceptorNames">
<list>
<value>traceBeforeAdvisor</value>
<value>traceAfterAdvisor</value>
</list>
</property>
</bean>
<!-- Advice classes -->
<bean id="tracingBeforeAdvice" class="TracingBeforeAdvice" />
<bean id="tracingAfterAdvice" class="TracingAfterAdvice" />
<!-- Advisor: way to associate advice beans with pointcuts -->
<!-- pointcut definition for before method call advice -->
<bean id="traceBeforeAdvisor"
class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
<property name="advice">
<ref local="tracingBeforeAdvice" />
</property>
<property name="pattern">
<!-- apply the advice to Hello class methods -->
<value>Hello.*</value>
</property>
</bean>
<!-- Advisor: way to associate advice beans with pointcuts -->
<!-- pointcut definition for after returning from the method advice -->
<bean id="traceAfterAdvisor"
class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
<property name="advice">
<ref local="tracingAfterAdvice" />
</property>
<!-- apply the advice to Hello class methods -->
<property name="pattern">
<value>Hello.*</value>
</property>
</bean>
</beans>
If you run the Test class again, you should get an output with AOP in action:
Just before method call...
Printing hello.
Just after returning from the method call...
45)   What are the differences between OOP and AOP?
OOP:
OOP looks at an application as a set of collaborating objects. OOP code scatters system level code like logging, security etc with the business logic code.
OOP nomenclature has classes, objects, interfaces etc.
Provides benefits such as code reuse, flexibility, improved maintainability, modular architecture, reduced development time etc with the help of polymorphism, inheritance and encapsulation.
AOP:
AOP looks at the complex software system as combined implementation of multiple concerns like business logic, data persistence, logging, security, multithread safety, error handling, and so on. Separates business logic code from the system level code. In fact one concern remains unaware of other concerns.

AOP nomenclature has join points, point cuts, advice, and aspects.
AOP implementation coexists with the OOP by choosing OOP as the base language. For example: AspectJ uses Java as the base language.
AOP provides benefits provided by OOP plus some additional benefits which are discussed in the next question.

46)  What are the benefits of AOP?

OOP can cause the system level code like logging, transaction management, security etc to scatter throughout the business logic. AOP helps overcome this problem by centralizing these cross-cutting concerns.

 AOP addresses each aspect separately in a modular fashion with minimal coupling and duplication of code.
This modular approach also promotes code reuse by using a business logic concern with a separate logger
aspect.

 It is also easier to add newer functionalities by adding new aspects and weaving rules and subsequently
regenerating the final code. This ability to add newer functionality as separate aspects enable application
designers to delay or defer some design decisions without the dilemma of over designing the application.

Promotes rapid development of evolutionary prototypes using OOP by focusing only on the business logic by omitting cross-cutting concerns such as security, auditing, logging etc. Once the prototype is accepted,
additional concerns like security, logging, auditing etc can be weaved into the prototype code to transfer it into a production standard application.

 Developers can concentrate on one aspect at a time rather than having to think simultaneously about business logic, security, logging, performance, multithread safety etc. Different aspects can be developed by different developers based on their key strengths. For example: A security aspect can be developed by a security expert or a senior developer who understands security.

47)   What is inversion of control (IoC) (also known more specifically as dependency injection)?

 Inversion of control or dependency injection (which is a specific type of IoC) is a term used to resolve object
dependencies by injecting an instantiated object to satisfy dependency as opposed to explicitly requesting an object. So objects will not be explicitly requested but objects are provided as needed with the help of an Inversion Of Controller container (e.g. Spring, Hivemind etc). This is analogous to the Hollywood principal where the servicing objects say to the requesting client code (i.e. the caller) “don’t call us, we’ll call you”. Hence it is called inversion of control.
Most of you all are familiar with the software development context where client code (requesting code)
collaborates with other dependent objects (or servicing objects) by knowing which objects to talk to, where to locate them and how to talk with them. This is achieved by embedding the code required for locating and
instantiating the requested components within the client code. The above approach will tightly couple the
dependent components with the client code.
Caller code:
class CarBO {
public void getCars(String color) {
//if you need to use a different implementation class say FastCarDAOImpl then need to
//make a change to the caller here (i.e. CarDAO dao = new FastCarDAOImpl()). so the
//caller is tightly coupled. If this line is called by 10 different callers then you
//need to make changes in 10 places.
CarDAO dao = new CarDAOImpl();
List listCars = dao.findCarsByColor(color);
}
}
Being called code:
interface CarDAO (){
public abstract List findCarsByColor(color);
}
interface CarDAOImpl extends CarDAO (){
public List findCarsByColor(color) {
//data access logic goes here
}
}
This tight coupling can be resolved by applying the factory design pattern and program to interfaces not to
implementations driven development.
Simplified factory class implemented with a singleton design pattern:
class CarDAOFactory {
private static final CarDAOFactory onlyInstance = new CarDAOFactory();
private CarDAOFactory(){}//private so that cannot be instantiated from outside the class
public CarDAOFactory getInstance(){
return onlyInstance;
}
public CarDAO getDAO(){
//if the implementation changes to FastCarDAOImpl then change here only instead of 10
//different places.
return new CarDAOImpl();
}
}
Now the caller code should be changed to:
class CarBO {
public void getCars(String color) {
//if you need to use a different implementation class say FastCarDAOImpl then need to
//make one change only to the factory class CarDAOFactory to return a different
//implementation (i.e. FastCarDAOImpl) rather than having to change all the callers.
CarDAO dao = CarDAOFactory.getInstance().getDAO();
List listCars = dao.findCarsByColor(color);
}
}
But the factory design pattern is still an intrusive mechanism because servicing objects need to be requested
explicitly. Also if you work with large software systems, as the system grows the number of factory classes can
become quite large. All the factory classes are simple singleton classes that make use of static methods and field
variables, and therefore cannot make use of inheritance. This results in same basic code structure repeated in all
the factory classes.
Let us look at how dependency injection comes to our rescue. It takes the approach that clients declare their
dependency on servicing objects through a configuration file (like spring-config.xml) and some external piece of
supplying the relevant references when needed to the client code whereby acting as the factory objects. This
external piece of code is often referred to as IoC (specifically known as dependency injection) container or
framework.
SpringConfig.xml
<beans>
<bean id="car" class="CarBO" singleton="false" >
<constructor-arg>
<ref bean="carDao" />
</constructor-arg>
</bean>
<bean id="carDao” class="CarDAOImpl" singleton="false" />
</beans>
Now your CarBO code changes to:
class CarBO {
private CarDAO dao = null;
public CarBO(CarDAO dao) {
this.dao = dao;
}
public void getCars(String color) {
//if you need to use a different implementation class say FastCarDAOImpl then need to
//make one change only to the SpringConfig.xml file to use a different implementation
//class(i.e. class=”FastCarDAOImpl”) rather than having to change all the callers.
List listCars = dao.findCarsByColor(color);
}
}
Your calling code would be (e.g. from a Web client or EJB client ):
ApplicationContext ctx = new FileSystemXmlApplicationContext("SpringConfig.xml");
//lookup “car” in your caller where “carDao” is dependency injected using the constructor.
CarBO bo = (CarBO)ctx.getBean("car"); //Spring creates an instance of the CarBO object with
//an instance of CarDAO object as the constructor arg.
String color = red;
bo.getCars(color)
You can use IoC containers like Spring framework to inject your business objects and DAOs into your calling
classes. Dependencies can be wired by either using annotations or using XML as shown above. Tapestry 4.0
makes use of the Hivemind IoC container for injecting application state objects, pages etc.
IoC or dependency injection containers generally control creation of objects (by calling “new”) and resolve
dependencies between objects it manages. Spring framework, Pico containers, Hivemind etc are IoC containers to name a few. IoC containers support eager instantiation, which is quite useful if you want self-starting services that “come up” on their own when the server starts. They also support lazy loading, which is useful when you have many services which may only be sparsely used.

48) What are the benefits of IoC (aka Dependency Injection)?

Minimizes the amount of code in your application. With IoC containers you do not care about how services are created and how you get references to the ones you need. You can also easily add additional services by
adding a new constructor or a setter method with little or no extra configuration.

Makes your application more testable by not requiring any singletons or JNDI lookup mechanisms in your unit test cases. IoC containers make unit testing and switching implementations very easy by manually allowing you to inject your own objects into the object under test.

Loose coupling is promoted with minimal effort and least intrusive mechanism. The factory design pattern is
more intrusive because components or services need to be requested explicitly whereas in IoC the
dependency is injected into the requesting code. Also some containers promote the design to interfaces not to implementations design concept by encouraging managed objects to implement a well-defined service
interface of your own.

IoC containers support eager instantiation and lazy loading of services. Containers also provide support for
instantiation of managed objects, cyclical dependencies, life cycle management, and dependency resolution
between managed objects etc.

LinkWithin

Related Posts Plugin for WordPress, Blogger...

Labels

Core Java programming core java interview question Core Java Faq's Servlets coding database jsp-servlet spring Java linux unix interview questions java investment bank Web Services Interview investment bank mysql Senior java developer interviews best practices java collection tutorial RMI SQL Eclipse FIX protocol tutorial tibco J2EE groovy java questions SCJP grails java 5 tutorial jdbc beginner error and exception Design Patterns Java Programming Tutorials fundamentals general object oriented programming xml Java Programs Hibernate Examples Flex JAMon Java xml tutorial logging Jsp Struts 2.0 Sybase and SQL Server debugging java interviews performance FIX Protocol interview questions JUnit testing WebSphere date and time tutorial experienced java IO tutorial java concurrency thread Ejb Freshers Papers IT Management Java Exapmle Java Script SQL and database tutorial examples Scwcd ant tutorials concurrency example and tutorial future state homework java changes java threading tricky Agile Business of IT Development JSTL Java JSON tutorial Java multithreading Tutorials PM Scrum data structure and algorithm java puzzles java tips testing tips windows 8 5 way to create Singleton Object Architect Interview Questions and Answers Architecture Architecure Bluetooth server as swing application that searches bluetooth device in 10 meter circle and show all devices. You can send file to any bluetooth device. C Programming CIO Callable Statement in Java Circular dependency of Objects in Java Comparable Example in Collection Custom annotation in Java Developer Interview Divide and rule example in java Drupal Example of Singleton Pattern FIX protocol ForkJoin Example in Java 7 Get data from dynamic table with Java Script Git HTML and JavaScript Health Hello World TCP Client Server Networking Program Hibernate Basics Hibernate Interview Question Answer J2EE Interview Question And Answers J2ME GUI Program JEE Interview QA JMS interview question Java J2EE Hibernate Spring Struts Interview Question Java System Property Java Threads Manager Portlets Provident Fund Read data from any file in same location and give the required result. Reading Properties File in Java Redpoint Rest WebService Client Rest Webservice Test SAL join with ven diagram SCP UNIX COMMAND SSL Singleton Pattern in Java Spring Bean Initialization methods and their order Spring Interview Questions Struts Struts 2.0 Basics Struts 2.0 Design Pattern Submit Html Form With Java Script On The Fly Unix executable For Java Program XOM DOM SAX XP books computers core java; core java; object oriented programming data structure; java investment bank; design pattern dtd duplicate rows in table get browser name with jquery grails podcast inner class java beginners tutorial java cache java networking tutorial java spring java util; java collections; java questions java.java1.5 linked list mailto function with all browser oracle database oracle duplicate rows orm schema social spring mvc questions struts transaction tricks tweet windows xslt