Spring Interview Questions & Answers


difference @bean and @component



Which design patterns are followed by Spring?

Reflection pattern
Factory pattern
Singleton pattern

How many types of dependency injections available in spring?

4 types.
  1. Constructor injection — good, rable and immutable, inject via one of the constructors. Possible to configure in: XML, XML+Annotations, Java, Java + Annotations.
  2. Setter injection — more flexible, mutable objects, injection via setters. Possible to configure in: XML, XML+Annotations, Java, Java + Annotations.
  3. Field injection — fast and convenient, coupling with IoC container. Possible to configure in XML+Annotations, Java + Annotations.
  4. Lookup method injection — totally different from others, used for injection dependency of smaller scope. Possible to configure in: XML, XML+Annotations, Java, Java + Annotations.

What is Bean scope in Spring MVC framework with Example
1) Singleton (default scope)
2) prototype
3) request
4) session
5) global-session

spring 3.0 with addition of few new scopes like thread scope or SimpleThreadScope  which is a scope backed by thread. 
u can also register your own custom scope using CustomScopeConfigurer utility., there is no new scope for bean is introduced on spring 3.0

Explain Autowire in spring
1.    @Autowired annotation used with setter methods, it tries to perform byType autowiring on the method.

2.    If 2 beans are defined with same type then we can use @Qualifier to use the name of the bean.

3.    You can apply @Autowired to constructors as well. A constructor @Autowired annotation indicates that the constructor should be autowired when creating the bean, even if no <constructor-arg> elements are used while configuring the bean in XML file.

4.    @Autowired with (required = false) option
By default, the @Autowired annotation implies the dependency is required similar to @Required annotation, however, you can turn off the default behavior by using (required=false) option with @Autowired.

5.    @Resource Annotation
You can use @Resource annotation on fields or setter methods and it works the same as in Java EE 5. The @Resource annotation takes a 'name' attribute which will be interpreted as the bean name to be injected. You can say, it follows by-name autowiring semantics as demonstrated in the following example −
package com.tutorialspoint;

import javax.annotation.Resource;

public class TextEditor {
   private SpellChecker spellChecker;

   @Resource(name = "spellChecker")
   public void setSpellChecker( SpellChecker spellChecker ){
      this.spellChecker = spellChecker;
   }
   public SpellChecker getSpellChecker(){
      return spellChecker;
   }
   public void spellCheck(){
      spellChecker.checkSpelling();
   }
}
If no 'name' is specified explicitly, the default name is derived from the field name or setter method. In case of a field, it takes the field name; in case of a setter method, it takes the bean property name.

Explain the use of @Configuration, @Bean @Import and @Scope
Annotating a class with the @Configuration indicates that the class can be used by the Spring IoC container as a source of bean definitions. The @Bean annotation tells Spring that a method annotated with @Bean will return an object that should be registered as a bean in the Spring application context. The simplest possible @Configuration class would be as follows −
package com.tutorialspoint;
import org.springframework.context.annotation.*;

@Configuration
public class HelloWorldConfig {

   @Bean 
   public HelloWorld helloWorld(){
      return new HelloWorld();
   }
}
The above code will be equivalent to the following XML configuration −
<beans>
   <bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld" />
</beans>
Here, the method name is annotated with @Bean works as bean ID and it creates and returns the actual bean. Your configuration class can have a declaration for more than one @Bean. Once your configuration classes are defined, you can load and provide them to Spring container using AnnotationConfigApplicationContext as follows −
public static void main(String[] args) {
   ApplicationContext ctx = new AnnotationConfigApplicationContext(HelloWorldConfig.class);
   
   HelloWorld helloWorld = ctx.getBean(HelloWorld.class);
   helloWorld.setMessage("Hello World!");
   helloWorld.getMessage();
}
You can load various configuration classes as follows −
public static void main(String[] args) {
   AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();

   ctx.register(AppConfig.class, OtherConfig.class);
   ctx.register(AdditionalConfig.class);
   ctx.refresh();

   MyService myService = ctx.getBean(MyService.class);
   myService.doStuff();
}


The @Import Annotation

The @Import annotation allows for loading @Bean definitions from another configuration class. Consider a ConfigA class as follows −
@Configuration
public class ConfigA {
   @Bean
   public A a() {
      return new A(); 
   }
}
You can import above Bean declaration in another Bean Declaration as follows −
@Configuration
@Import(ConfigA.class)
public class ConfigB {
   @Bean
   public B b() {
      return new B(); 
   }
}
Now, rather than needing to specify both ConfigA.class and ConfigB.class when instantiating the context, only ConfigB needs to be supplied as follows −
public static void main(String[] args) {
   ApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigB.class);
   
   // now both beans A and B will be available...
   A a = ctx.getBean(A.class);
   B b = ctx.getBean(B.class);
}

Lifecycle Callbacks

The @Bean annotation supports specifying arbitrary initialization and destruction callback methods, much like Spring XML's init-method and destroy-method attributes on the bean element −
public class Foo {
   public void init() {
      // initialization logic
   }
   public void cleanup() {
      // destruction logic
   }
}
@Configuration
public class AppConfig {
   @Bean(initMethod = "init", destroyMethod = "cleanup" )
   public Foo foo() {
      return new Foo();
   }

  public void init() {
  }
}

Specifying Bean Scope

The default scope is singleton, but you can override this with the @Scope annotation as follows −
@Configuration
public class AppConfig {
   @Bean
   @Scope("prototype")
   public Foo foo() {
      return new Foo();
   }
}


How many ways to load the spring context file in web application?
There are 2 ways

1. If your application is WebMVC using DispatchServlet then you can pass file name in servlet's init parameters.
For Example
     <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring-servlet.xml</param-value>
    </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

2. You can use ContextLoaderListener and context paramters using below line to load the file.
For Example

<listener> 
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>   
</listener>
<context-param>  
            <param-name>contextConfigLocation</param-name>  
            <param-value>  
                /WEB-INF/spring-servlet.xml  
                /WEB-INF/spring-security.xml  
            </param-value>  
        </context-param>  


How to integrate Hibernate with Spring and get SessionFactory object?

As we know, we have to load the configuration file in the hibernate first. this configuration file  (hibernate.cfg.xml) contains database related information. when we load the hibernate configuration file then we get the configuration object pertaining datasource object. then we ask configuration object to buildSessionFactory object.

1. Similarly in spring context file we create bean for datasource using apache lib.
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <beans:property name="driverClassName" value="com.mysql.jdbc.Driver" /> <beans:property name="url" value="jdbc:mysql://localhost:3306/TestDB" /> <beans:property name="username" value="pankaj" /> <beans:property name="password" value="pankaj123" /> </beans:bean>

2. Now we need to create sessionfactory object using below bean providing datasource bean id, which we have created just above.

<!-- Hibernate 4 SessionFactory Bean definition --> <beans:bean id="hibernate4AnnotatedSessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <beans:property name="dataSource" ref="dataSource" /> <beans:property name="annotatedClasses"> <beans:list> <beans:value>com.journaldev.spring.model.Person</beans:value> </beans:list> </beans:property> <beans:property name="hibernateProperties"> <beans:props> <beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect </beans:prop> <beans:prop key="hibernate.show_sql">true</beans:prop> </beans:props> </beans:property> </beans:bean>

3. Now we can associate transaction manager with this sessionfactory using below lines.
<tx:annotation-driven transaction-manager="transactionManager"/> <beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" /> </beans:bean>

4. Inject above created sessionfactory object in your dao class.
<beans:bean id="personDAO" class="com.journaldev.spring.dao.PersonDAOImpl"> <beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" /> </beans:bean>

How to connect DB using JNDI in spring?
<!-- Create DataSource Bean --> <beans:bean id="dbDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">       <beans:property name="jndiName" value="java:comp/env/jdbc/MyLocalDB"/> </beans:bean> <!-- using JEE namespace for lookup --> <!-- <jee:jndi-lookup id="dbDataSource" jndi-name="jdbc/MyLocalDB" expected-type="javax.sql.DataSource" /> -->

Tomcat DataSource JNDI Configuration

Now that we are done with our project, the final part is to do the JNDI configuration in Tomcat container to create the JNDI resource.

<Resource name="jdbc/TestDB" 
      global="jdbc/TestDB" 
      auth="Container" 
      type="javax.sql.DataSource" 
      driverClassName="com.mysql.jdbc.Driver" 
      url="jdbc:mysql://localhost:3306/TestDB" 
      username="pankaj" 
      password="pankaj123" 
      
      maxActive="100" 
      maxIdle="20" 
      minIdle="5" 
      maxWait="10000"/>
Add above configuration in the GlobalNamingResources section of the server.xml file.

<ResourceLink name="jdbc/MyLocalDB"
                 global="jdbc/TestDB"
                    auth="Container"
                    type="javax.sql.DataSource" />
We also need to create the Resource Link to use the JNDI configuration in our application, best way to add it in the server context.xml file.
Notice that ResourceLink name should be matching with the JNDI context name we are using in our application. Also make sure MySQL jar is present in the tomcat lib directory, otherwise tomcat will not be able to create the MySQL database connection pool.

How to serve static content of web application using spring xml?

<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />



Since we are using WebApplicationInitializer, the web.xml file is NOT required.


Inject and Resource and Autowired annotations?

@Autowired: spring propriety annotation (as opposed to @Inject and @Resource) that inject a resource by-type, i.e. by the class of by the interface of the annotated field or contractor. In case we have few implementation of an interface or a subclass we can narrow down the selection using the @Qualifier annotation to avoid ambiguity. For a fallback match, the bean name is considered a default qualifier value. Although you can use this convention to refer to specific beans by name, @Autowired is fundamentally about type-driven injection with optional semantic qualifiers.

@Inject: Annotation based on JSR-330 (Dependency Injection for Java) identifies injectable constructors, methods, and fields. This annotation is an almost complete drop-in replacement for Spring’s @Autowired annotation. So, instead of using the Spring-specific @Autowired annotation, you might choose to use @Inject. One of the differences between @Autowired and @Inject is that @Inject does not have the required field so in case we fail to find a suitable object to inject it will fail while @Autowired can used required=false and allow null able field (only if required!). Advantage of @Inject annotation is that rather than inject a reference directly, you could ask @Inject to inject a Provider. The Provider interface enables, among other things, lazy injection of bean references and injection of multiple instances of a bean. In case we have few implementation of an interface or a subclass we can narrow down the selection using the @Named annotation to avoid ambiguity. @Named annotation works much like Spring’s @Qualifier

@Resource: annotation based on JSR-250. @Resource is quite similar to @Autowired and @Inject, but the main difference is the execution paths taken to find out the required bean to inject. @Resource will narrow down the search first by name then by type and finally by Qualifiers (ignored if match is found by name). @Autowired and @Inject will narrow down the search first by type then by qualifier and finally by the name.






SHARE

esant technology

0 comments :

Post a Comment