Pages

Friday, November 8, 2013

Top 10 Spring 3 interview questions - Beginners

1) How do you use annotations with Spring & How do you instruct Spring to scan the source code to pick up the annotations?

In the spring context file these two elements has to be declared to instruct spring that, the project is using annotations & it needs to scan the packages to pick up those annotations and create objects.

<context:annotation-config />
<context:component-scan base-package="com.ravi" />


2) How do you do jndi lookup with Spring?

The simple way to do this is to use the jndi-lookup that comes with jee namespace. Example as below. You need to declare that name space also in the spring context file.

    <jee:jndi-lookup id="jms_connectionFactory"    resource-ref="true" jndi-name="jms/SAMPLE_CF"/>
   
    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee"    
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/jee
                           http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">
                          
3) How do you load property files with Spring?

You have property files in the application which you want to load to use in the application. You should use the property-placeholder element in the context namespace to do this. Example as below.

<context:property-placeholder location="classpath*:example.properties"
        order="1" ignore-unresolvable="true" />
       
log.file.location=c:\logfilelocation
jdbc.dialect=Oracle10g
hibernate.show_sql=true
       
In the application code you can use it like this to get a specific value of the property.
You should use @Value annotation to load the property.

@Service
public class ExamplePropertyLoader
{
@Value(value = "${log.file.location}")
String logFileLocation;
}

Please note for the above approach to work, the class has to be instantiated by spring through component scanning. For example if you create the instance of ExamplePropertyLoader the logFileLocation value will be loaded.  Also for static fields this approach will not work.

To use it in the spring context file itself you can use it like this

<property name="hibernateProperties">
<props>
    <prop key="hibernate.dialect">${jdbc.dialect}</prop>
    <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>

4) How do you use one spring context file in another context file?

Spring supports a concept called import using which one context file can be imported in to another.For example you define database related spring configurations like data source lookup, property file look up in a separate context file and then import that in the other context file instead of repeating this in every context files.

For example the access-common-db-context.xml contains all the information about database and then you can import it using

<import resource="classpath:access-common-db-context.xml" />

5) Can you declare class level (instance) variables in Spring Controller?

Controllers are by default singleton classes. Meaning there will be only one instance. So if there are class level variables then, the values are shared across multiple requests. For example, if there is a counter variable in the controller and you increase the counter for each call. When user 1 calls the controller the value will be increased by 1 and when next user (user 2) calls the controller the value will be 2 because of this shared nature. So one should avoid declaring class level variables in the Controllers.

6) What are the mostly used annotations in Spring?

@Autowired
@Component
@Qualifier
@Value
@Controller
@RequestMapping

7) How do you configure transactions using Spring?

TBD

8) How do you handle exceptions in Spring MVC?

Spring comes with default exception resolvers. One way of handling exception is to extend the DefaultHandlerExceptionResolver class and override the doResolveException method.

    @Override
    protected ModelAndView doResolveException(final HttpServletRequest request,
            final HttpServletResponse response, final Object handler,
            final Exception ex) {
            ModelAndView mav = null;
            mav = new ModelAndView("error/errorpage");
            return mav;
            }
           
Once this exception resolver configured in the Spring context file, any uncaught exceptions automatically re-directed to this class and here it can be directed to an error page.

9) How do you externalize and configure message labels of screens in Spring MVC?

Use ResourceBundleMessageSource class to externalize the message labels used in your screens. There should be a file called screen_text in the classpath which contains the key and values.

<bean id="messageSource"
        class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basenames">
            <list>
                   <value>screen_text</value>
            </list>
        </property>
        <property name="useCodeAsDefaultMessage">
            <value>true</value>
        </property>
</bean>

Contents of screen_text

general.error.title=Sample Error Screen
general.error.message=There is a problem with the application. Contact system admin for further details.

10) How do you configure interceptors in Spring MVC?

Use interceptors tag that comes in the mvc name space to configure interceptors for your application. Once the interceptors configured in the context file, they are automatically invoked for every request.

<mvc:interceptors>      
        <bean class="com.ravi.web.interceptor.AuthInterceptor" />    
</mvc:interceptors>

This interceptor class has to extend HandlerInterceptorAdapter class. This HandlerInterceptorAdapter class provides the default implementation for preHandle, postHandle, afterCompletion, afterConcurrentHandlingStarted etc. If you want to check for example, every request has the logged in, user information you can do that
like this

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception
{
     HttpSession session = request.getSession();
     if(session.get("loggedInUser") == null)
     return true;
}

No comments:

Post a Comment

 
Blogger Templates