Interview questionsJavaSpring

Spring Interview questions

What is Dependency Injection in Spring ?

  • Dependency injection helps you to avoid unnecessary creation and lookup code in your application. If a class X, requires Class Y’s functionalities, we don’t have to write code to create class Y’s instance . Spring framework uses Dependency Injection and injects object of Y into object of X at runtime.
  • Dependency injection promotes loose coupling.
  • Dependency injection paves the way for removal of the factory and utility classes that we write in the application.
  • Dependency injection is also known as Inversion of Control or IoC. IoC refers to the control of creating and construction of objects being taken care by the container. The container creates objects and injects them into the application.

Explain Spring Configuration

Spring containers act as repository for all the configured beans. The containers instantiate the beans, populate their properties, and call the init method, which makes the bean ready to be used. During the shutdown of the application, destroy method of the bean is invoked. The init and destroy methods are used to perform initialization and clean up operations, such as opening and closing file streams.

What is Bean Factory ?

  • It is the basic container.
  • All other possible classes that act as containers implement BeanFactory.
  • This is the root container that loads all the beans and provides dependency injection to enterprise applications.

Here are some classes that implement BeanFactory:

1) XmlBeanFactory : Reads the bean definitions from an XML file and instantiates them.
2) StaticListableBeanFactory : All beans managed by this class are singletons.

These classes use implementation classes of Resource interface to read the configuration file.

What is Resource interface ?

Resource interface is the base interface that provides access to the spring configuration resources.

Here are some classes that implement the Resource interface:

1) ClassPathResource : Loads the config file using the file path or through a class that loads the config file.
2) FilesystemResource : Loads the config file by specifying the path.
3)PortletConextResource : loads resources within portlet application.
4) ServletcontextResource : loads resources within web application.
5)UrlResource : loads resources by providing the url.

Example:

BeanFactory factory = new XmlBeanFactory(new ClasspathResource(“bean.xml”));
BeanClassName bean = factory.getBean(“id of bean”, BeanClassName.class);

  • BeanFactory is a lazy container, which means that it instantiates the bean and configures it only when the getBean() method is called.

  • BeanFactory container is usually used in very simple applications; however, in real time projects, ApplicationContextContainer is used.

What is ApplicationContext ?

  • widely used as container in enterprise applications.
  • It is an advanced container that extends BeanFactory container with various enterprise-level feature, like:

1) Resolves message bundles and helps in internationalizing the applications.
2) Integrates with Spring AOP to generate proxy classes.
3) Publishes events to all the registered subscribers.

Here are some classes that implement Applicationcontext :
1) FileSystemXmlApplicationcontext : loads the xml config file from the file system and creates the context.
2) XmlWebApplicationContext : creates the context in web application by reading resources from standard locations in the web application directory.
3) XmlPortletApplicationContext : creates the context in web application by reading resources from standard locations in the portlet application directory.
4) AnnotationConfigApplicationcontext : creates the context by loading classes annotated with pre-defined annotations.
5) AnnotationConfigWebApplicationcontext : creates web application context by loading the classes annotated with pre-defined annotations in web applications.

Example:

ApplicationContext context = new FileSystemXmlApplicationContext (“class path:bean.xml”);
BeanClassName bean = context.getBean(“id of bean”, BeanClassName.class);

Compare ApplicationContext vs BeanFactory

  • ApplicationContext, unlike BeanFactory, is an active container. It instantiates all configured beans when the application is launched and before the user calls the getBean() method. The creation of beans happens as soon as the instance of ApplicationContext is created.
  • One advantage of active creation of beans is the handling of exceptions. If exception is thrown during creation of a bean, it can be handled during startup of the application itself.
  • The other advantage is that, time taken to create the beans is a non-issue as it is done in the beginning itself.
  • bean creation can be configured to be a lazy process by adding lazy-init attribute to the element.

setter-based injection:

  • Primitive values and reference values can be injected through the setter property.
  • The tag enables to inject values. It has the name attribute for the name of the property and value attribute and ref attribute to inject primitive values, Strings and reference values.

constructor based injection:

  • uses constructors in beans for injecting values.
  • tag is used to configure a constructor parameter.. two tags indicate two parameters.
  • it has an optional index attribute for param position, optional type attribute for type of the constructor argument and value/ref attribute for values or references.

Choice of constructor-based or setter-based dependency injection depends on whether we use constructors of properties to initialize variables.

Explain Auto-wiring in Spring

  • Spring provides auto-wiring facility to wire beans together without having to configure using the or tags.
  • Auto-wiring is enabled using the autowire attribute in the tag.
  • not used widely as it paves way for poor readability and maintenance.

Different values of autowire attribute are as follows:
1) byName – the bean looks for other beans with same name as the property.
2) byType – the bean looks for other beans with same type as the property.
3) constructor – bean looks for other beans with the same type as the constructor argument.
4) no – not enabled by default.

What are various Bean Scopes in spring ?

  • tag has a scope attribute that configures scope of a bean.

1) singleton : only instance of bean created in the container.
2) prototype : creates a new instance every time the bean is accessed using getBean() method.
3) request : creates an instance of the bean for every HTTP request.
4) session : creates an instance of the bean for every HTTP session.
5) global-session : creates an instance of the bean for every port let session.

Parent attribute

parent attribute in helps to reuse config parameters.

  • all the properties configured in the parent bean are available to the inheriting bean.

Spring Annotations

1) Component : Used at the class level and configures the class as a bean.
2) Service : Used on service classes and is a type of @Component.
3) Repository : Used on DAO classes and is a type of @Component.
4) Autowired : Used on a field, method or constructor. The item that is marked with @Autowired annotation is injected after the bean is constructed.
5) Scope : used to specify the scope of the beans.
6) Lazy : used to enable lazy initialization of beans.
7) Required : Used on a setter property that forces dependency injection. If the appropriate bean is not found, it throws exception.

Spring provides the tag present in the Spring Context namespace that scans the specified package for classes annotated with @Component classes and its derivatives, and registers them as beans with the container. It has a base-package attribute that can be used to specify the comma separated list of packages to scan.

For instance, if com.config package contains the @Component classes, then component-scan element can be configured as :

 

What is jdbcTemplate ?

  • Serves as core class for JDBC operations with the Spring framework.
  • It uses the core JDBC api to create connections and statements while executing SQL queries.
  • The DAO classes should have a reference to the JdbcTemplate class and a setter method for injection by the Spring container.
  • The JdbcTemplate class has execute, query and update methods.

execute methods
———
– Overloaded execute methods of JdbcTemplate class are used to execute queries, prepared statements and procedures.
– normal queries can be run using jdbcTemplate.execute(query);
– syntax for executing prepared statement is execute(String sql, PreparedStatementCallback pstmt)
PreparedStatementCallback has just one method that needs to be implemented : doInPreparedStatement(PreparedStatement pstmt)
– syntax for executing callable statement is execute(String sql, CallableStatementCallback cstmt)

query methods
—————
The overloaded query methods are used to fetch data from the database.
– queryForObject
– queryForInt
– queryForList
– queryForMap
– queryForRowSet

  • queryForRowSet method accepts SQL query to be executed and returns a RowSet.
  • ResultSetExtractor is a callback interface for query() method. It accepts a ResultSet and converts it into a list.

  • RowMapper is a callback interface that allows you to map rows of ResultSet to the person objects. Unlike ResultSetExtractor, you do not need to iterate ResultSet and add it to the collection. Instead, the mapRow() method maps each record and adds the record to a collection.

update methods
————
– overloaded update methods are used to execute delete or update queries.

NamedParameterJdbcTemplate class

  • used to write queries with named parameters instead of question mark.
    insert into person values(:id, :name);

A map object can be used to pass the parameters. Both the map and the query are passed to the execute() method.

SimpleJdbcTemplate class

  • This class provides JDBC operations using features of Java 5, such as variable number of arguments and auto boxing.
  • It acts as a wrapper class around the JdbcTemplate class.

MappingSqlQuery class

Used for representing queries so that they can be reused easily.

Executing stored porcedures

  • jdbcTemplate.execute has a parameter for CallableStatmentCallback interface. The doInCallableStatement method of it can be used to execute the procedure.
  • Spring also provides a StoredProcedure class for the representation and execution of stored procedures.

Batch Processing

For batch updates, BatchPreparedStatementSetter interface needs to be used. It has following methods-
int getBatchSize –
void setValues(PreparedStatement pstmt, int index) – specifies how values are passed to prepared statement.

jdbcTemplate.batchUpdate() method takes the query as the 1st parameter and the implementation of BatchPreparedStatementSetter as the second parameter.

JdbcDaoSupport classes

  • All the dao classes need to have a reference to the Template classes, which leads to duplication of code. So, Spring provided JdbcDaoSupport classes.
  • so, jdbcTemplate.update() can be called as getJdbcTemplate().update() or getSimpleJdbcTemplate().update() or getNamedParameterJdbcTemplate().execute().

JMS with Spring

JMS messaging models are:

1) Publisher-Subscriber model: Application post messages to Topics and the subscribers receive it.
2) Point-to-Point model : Sender posts the msg to the queue and receiver receives it from the queue. There is only one receiver per message.

jmsTemplate

  • key class in Spring JMS. The publish and consume messages use the methods of this class.
  • JmsTemplate’s send() method can be used to send messages and receive() can be used to receive messages asynchronously.

© 2015, www.techkatak.com. All rights reserved.