Questions and answers taken from real job interviews.
Find interview questions and answers on this website:
Limitations of autowiring are: • Overriding: You can still specify dependencies using <constructor-arg> and <property> settings which will always override autowiring. • Primitive data types: You cannot autowire simple properties such as primitives, Strings, and Classes. • Confusing nature: Autowiring is less exact than explicit wiring, so if possible prefer using explicit wiring.
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. The most commonly used BeanFactory implementation is the XmlBeanFactory class.
The most useful one is org.springframework.beans.factory.xml.XmlBeanFactory, which loads its beans based on the definitions contained in an XML file. This container reads the configuration metadata from an XML file and uses it to create a fully configured system or application.
• The spring container finds the bean’s definition from the XML file and instantiates the bean. • Spring populates all of the properties as specified in the bean definition (DI). • If the bean implements BeanNameAware interface, spring passes the bean’s id to setBeanName() method. • If Bean implements BeanFactoryAware interface, spring passes the beanfactory to setBeanFactory() method. • If there are any bean BeanPostProcessors associated with the bean, Spring calls postProcesserBeforeInitialization()method. • If the bean implements IntializingBean, its afterPropertySet() method is called. If the bean has init method declaration, the specified initialization method is called. • If there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called. • If the bean implements DisposableBean, it will call the destroy() method.
The autowiring functionality has five modes which can be used to instruct Spring container to use autowiring for dependency injection: • no: This is default setting. Explicit bean reference should be used for wiring. • byName: When autowiring byName, the Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same names in the configuration file. • byType: When autowiring by datatype, the Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in configuration file. If more than one such beans exist, a fatal exception is thrown. • constructor: This mode is similar to byType, but type applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised. • autodetect: Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType.
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.
There are five scoped provided by the Spring Framework supports following five scopes: • In singleton scope, Spring scopes the bean definition to a single instance per Spring IoC container. • In prototype scope, a single bean definition has any number of object instances. • In request scope, a bean is defined to an HTTP request. This scope is valid only in a web-aware Spring ApplicationContext. • In session scope, a bean definition is scoped to an HTTP session. This scope is also valid only in a web-aware Spring ApplicationContext. • In global-session scope, a bean definition is scoped to a global HTTP session. This is also a case used in a web-aware Spring ApplicationContext. The default scope of a Spring Bean is Singleton.
This is the basic Spring module, which provides the fundamental functionality of the Spring framework. BeanFactory is the heart of any spring-based application. Spring framework was built on the top of this module, which makes the Spring container.
With the JDBC abstraction and DAO module we can be sure that we keep up the database code clean and simple, and prevent problems that result from a failure to close database resources. It provides a layer of meaningful exceptions on top of the error messages given by several database servers. It also makes use of Spring?s AOP module to provide transaction management services for objects in a Spring application.
Spring also supports for using of an object/relational mapping (ORM) tool over straight JDBC by providing the ORM module. Spring provides 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.
MVC framework is provided by Spring for building web applications. Spring can easily be integrated with other MVC frameworks, but Spring?s MVC framework is a better choice, since it uses IoC to provide for a clean separation of controller logic from business objects. With Spring MVC you can declaratively bind request parameters to your business objects.
The Spring web 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.
When using the Spring JDBC framework the burden of resource management and error handling is reduced. So developers only need to write the statements and queries to get the data to and from the database. JDBC can be used more efficiently with the help of a template class provided by Spring framework, which is the JdbcTemplate .
Use Spring?s SessionFactory called LocalSessionFactory. The integration process is of 3 steps: Configure the Hibernate SessionFactory Extend a DAO Implementation from HibernateDaoSupport Wire in Transaction Support with AOP
Spring offers the following types of collection configuration elements: • The <list> type is used for injecting a list of values, in the case that duplicates are allowed. • The <set> type is used for wiring a set of values but without any duplicates. • The <map> type is used to inject a collection of name-value pairs where name and value can be of any type. • The <props> type can be used to inject a collection of name-value pairs where the name and value are both Strings.
Check the following example: <?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-3.0.xsd"> <bean > <property name="message" value="Hello World!"/> </bean> </beans>
When defining a <bean> in Spring, we can also declare a scope for the bean. It can be defined through the scope attribute in the bean definition. For example, when Spring has to produce a new bean instance each time one is needed, the bean’s scope attribute to be prototype. On the other hand, when the same instance of a bean must be returned by Spring every time it is needed, the the beanscope attribute must be set to singleton.
There are three important methods to provide configuration metadata to the Spring Container: • XML based configuration file. • Annotation-based configuration • Java-based configuration
• Following is the list of few of the g reat benefits of using Spring Framework: -Lig htweig ht: Spring is lig htweig ht when it comes to size and transparency. T he basic version of spring framework is around 2MB. -Inversion of c ontrol (IO C): Loose coupling is achieved in spring using the technique Inversion of Control. T he objects g ive their dependencies instead of creating or looking for dependent objects. -Aspec t oriented (AO P): Spring supports Aspect oriented prog ramming and enables cohesive development by separating application business log ic from system services. -Container: Spring contains and manag es the life cycle and config uration of application objects. MVC Framework: Spring 's web framework is a well-desig ned web MVC framework, which provides a g reat alternative to web frameworks such as Struts or other over eng ineered or less popular web frameworks. -T ransac tion Manag ement: Spring provides a consistent transaction manag ement interface that can scale down to a local transaction (using a sing le database, for example) and scale up to g lobal transactions(using JT A, for example). -Exc eption Handling : Spring provides a convenient API to translate technolog y-specific exceptions (thrown by JDBC, Hibernate, or JDO, for example) into consistent, unchecked exceptions.
The Spring Beans are Java Objects that form the backbone of a Spring application. They are instantiated, assembled, and managed by the Spring IoC container. These beans are created with the configuration metadata that is supplied to the container, for example, in the form of XML <bean/> definitions. Beans defined in spring framework are singleton beans. There is an attribute in bean tag named "singleton" if specified true then bean becomes singleton and if set to false then the bean becomes a prototype bean. By default it is set to true. So, all the beans in spring framework are by default singleton beans.
T he main benefits of IOC or dependency injection are: It minimizes the amount of code in your application. It makes your application easy to test as it doesn't require any sing letons or JNDI lookup mechanisms in your unit test cases. Loose coupling is promoted with minimal effort and least intrusive mechanism. IOC containers support eag er instantiation and lazy loading of services.
• It provides a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, JPA, and JDO. • It provides a simpler API for programmatic transaction management than a number of complex transaction APIs such as JTA. • It supports declarative transaction management. • It integrates very well with Spring’s various data access abstractions.
• Constructor-based dependency injection: Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on other class. • Setter-based dependency injection: Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.
• An interface that defines the functions. • The implementation that contains properties, its setter and getter methods, functions etc., • Spring AOP • The Spring configuration XML file. • Client program that uses the function
Aspect-oriented prog ramming , or AOP, is a prog ramming technique that allows prog rammers to modularize crosscutting concerns, or behavior that cuts across the typical divisions of responsibility, such as log g ing and transaction manag ement. T he core construct of AOP is the aspect, which encapsulates behaviors affecting multiple classes into reusable modules.
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 a clean separation of controller logic from business objects. It also allows to declaratively bind request parameters to business objects.
Inversion of Control (IoC) is a g eneral concept, and it can be expressed in many different ways and Dependency Injection is merely one concrete example of Inversion of Control. T his concept says that you do not create your objects but describe how they should be created. You don't directly connect your components and services tog ether in code but describe which services are needed by which components in a config uration file. A container (the IOC container) is then responsible for hooking it all up.
Dependency Injection, an aspect of Inversion of Control (IoC), is a general concept, and it can be expressed in many different ways.This concept says 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 (the IOC container) is then responsible for hooking it all up.
Spring config uration file is an XML file. This file contains the classes information and describes how these classes are config ured and introduced to each other.
T he Spring IoC creates the objects, wire them tog ether, config ure them, and manag e their complete lifecycle from creation till destruction. T he Spring container uses dependency injection (DI) to manag e the components that make up an application.
Java based configuration option enables you to write most of your Spring configuration without XML but with the help of few Java-based annotations. An example is the @Configuration annotation, that indicates that the class can be used by the Spring IoC container as a source of bean definitions. Another example is the@Bean annotated method that will return an object that should be registered as a bean in the Spring application context.
Spring is an open source development framework for Enterprise Java. The core features of the Spring Framework can be used in developing any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring framework targets to make Java EE development easier to use and promote good programming practice by enabling a POJO-based programming model.
Application contexts provide a means for resolving text messages, a generic way to load file resources (such as images), they can publish events to beans that are registered as listeners. In addition, 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. The application context implements MessageSource, an interface used to obtain localized messages, with the actual implementation being pluggable.
The Concern is behavior we want to have in a module of an application. A Concern may be defined as a functionality we want to implement. The cross-cutting concern is a concern which is applicable throughout the application and it affects the entire application. For example, logging, security and data transfer are the concerns which are needed in almost every module of an application, hence they are cross-cutting concerns.
Since you can mix both, Constructor- and Setter-based DI, it is a g ood rule of thumb to use constructor arg uments for mandatory dependencies and setters for optional dependencies. Note that the use of a @Required annotation on a setter can be used to make setters required dependencies.
The basic modules of the Spring framework are : • Core module • Bean module • Context module • Expression Language module • JDBC module • ORM module • OXM module • Java Messaging Service(JMS) module • Transaction module • Web module • Web-Servlet module • Web-Struts module • Web-Portlet module