Prev Next

Spring / Spring Interview questions II

1. Differentiate commandName and modelAttribute. 2. Can I make a path variable optional? 3. Difference between @Inject and @Autowired in Spring Framework. 4. How can JDBC be used more efficiently in the Spring framework? 5. How do I prevent XSS attack at JSP HTML form? 6. What are the advantage of form:label tag in Spring? 7. Where do I place the robots.txt or sitemap.xml or any other file in my web application? 8. Recommended method for escaping HTML using Java. 9. Difference between @Controller and @RestController annotation in Spring MVC. 10. How to retrieve Session Object In Spring MVC? 11. What are the RequestMapping Variants in Spring MVC framework? 12. How do I implement caching in Spring framework? 13. Can a bean class with private constructor be instantiated in Spring framework? 14. Difference between spring singleton bean and the Gang of Four singleton pattern in Java. 15. How do we inject a null or empty Value in Spring framework? 16. What are the different types of events in spring framework? 17. Difference between FileSystemResource and ClassPathResource in Spring framework. 18. Name some of the design patterns used in Spring Framework. 19. Difference between @Bean and @Component annotations in Spring. 20. How do you integrate spring into your Java application? 21. How do I get ServletContext and ServletConfig object in a Spring Bean? 22. What are the different types of Listener events in Spring? 23. How do I resolve codes to error messages in Spring validation? 24. Advantages of PropertyEditor in spring. 25. Explain the role of ConverterFactory in spring validation. 26. Explain Validator interface in Spring. 27. What happens when a prototype bean is injected into a singleton bean? 28. How do you read property files using Spring? 29. Difference between ref bean and ref local attribute in Spring. 30. Why is ApplicationContext.getBean considered bad in Spring? 31. How do I remove a spring bean from ApplicationContext? 32. Difference between JDK dynamic proxy and CGLib proxy in Spring. 33. What are the limitations for auto-wiring by the constructor in Spring? 34. Explain @Configurable annotation in Spring. 35. What is the main strategy interface in Spring security? 36. How to logout the session in spring security? 37. How does Prototype scope work in spring? 38. Can you use @Autowired annotation with static field members? 39. Mention the key interface in that abstracts Spring framework transactions. 40. How to load spring beans from the dependency jar in my project? 41. Explain @Configuration annotation in Spring. 42. What is the difference between @Configuration and @Component in spring? 43. Difference between @Bean and @Component annotation in spring. 44. Explain fixedDelay and fixedRate properties in Spring @Scheduled Annotation. 45. What is Spring SSE? 46. Advantages of SSE over Websockets. 47. Advantages of Websockets over SSE.
Could not find what you were looking for? send us the question and we would be happy to answer your question.

1. Differentiate commandName and modelAttribute.

Both are similar and has no difference.

2. Can I make a path variable optional?

No. In spring MVC path variables are mandatory, however, we may have two controller methods that call the same service code:

@RequestMapping(value="/module/{path}", method=RequestMethod.GET)
public @ResponseBody String mapRequest(HttpServletRequest req, @PathVariable String path) {
        return processRequest();
}

@RequestMapping(value="/module", method=RequestMethod.GET)
public @ResponseBody String mapRequest(HttpServletRequest req) {
       return processRequest();
}

3. Difference between @Inject and @Autowired in Spring Framework.

@Inject is part of the Java CDI (Contexts and Dependency Injection) standard introduced in Java EE 6.

@Autowired is Spring's own annotation. @Inject is part of CDI that defines a standard for dependency injection similar to Spring.

In any Spring application, the two annotations works the same way as Spring extends its support to CDI.

4. How can JDBC be used more efficiently in the Spring framework?

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.

5. How do I prevent XSS attack at JSP HTML form?

There are three easy ways.

To implement the HTML escape at the entire application level, add the following at the web.xml.

<context-param>
    <param-name>defaultHtmlEscape</param-name>
    <param-value>true</param-value>
</context-param>

For all forms on a given JSP page,

<spring:htmlEscape defaultHtmlEscape="true" /> 

For each form:

<form:input path="formFieldName" htmlEscape="true" /> 

6. What are the advantage of form:label tag in Spring?

The <form:label /> tag has access to the underlying model and binding results, so on error, it can use another style class. 

<form:label cssClass="empClass" cssErrorClass="empErrorClass" path="empName" />

7. Where do I place the robots.txt or sitemap.xml or any other file in my web application?

Place the file at the context root of the application.

All urls are handled by Spring MVC DelegatingFilterProxy , so we need to exclude *.txt, *.xml from this filter. To exclude,

<mvc:resources mapping="/robots.txt" location="/WEB-INF/robots.txt" order="0"/>	

<mvc:resources mapping="/sitemap.xml" location="/WEB-INF/sitemap.xml" order="0"/>	

8. Recommended method for escaping HTML using Java.

Using Spring's HtmlUtils.htmlEscape(String input) method.

package com.tutorials.spring;

import org.springframework.web.util.HtmlUtils;

public class HTMLEscape {

	public static void main(String[] args) {
		String source = "The less than sign (<) and ampersand (&) will be escaped before using it in HTML";

		System.out.println(HtmlUtils.htmlEscape(source));
	}

}

Output:
The less than sign (&amp;lt;) and ampersand (&amp;amp;) must be escaped before using them in HTML.

9. Difference between @Controller and @RestController annotation in Spring MVC.

@Controller denotes that the marked class is a Spring MVC Controller.

@RestController is nothing but a combination of @Controller and @ResponseBody annotations. @RestController annotation marks any class as @Controller and in addition to that it annotates the class with the @ResponseBody annotation.

The following controller definitions are functionally equal.

@Controller
@ResponseBody
public class MVCController { }

@RestController
public class MVCController { }

10. How to retrieve Session Object In Spring MVC?

Getting HttpSession Object in Spring Controller is simple. We just need to add HttpSession as a method parameter in controller method and Spring will automatically inject it .

Or, inject the HttpServletRequest Object to the controller method and get the session object from it by calling getSession method.

Another approach is to create a Session scoped Controller using @scope annotation. This Controller get created for each session and controller object is stored in session.

Or one can create a session scoped component and inject It to your controller as shown below.

Another method is to use Scoped proxy.

11. What are the RequestMapping Variants in Spring MVC framework?

Spring Framework 4.3 introduces the method-level composed variants of the @RequestMapping annotation that helps simplifying the mappings for common HTTP methods and better express the semantics of the annotated handler method. For example, a @GetMapping can be interpreted as a GET @RequestMapping.

  • @GetMapping.
  • @PostMapping.
  • @PutMapping.
  • @DeleteMapping.
  • @PatchMapping.
12. How do I implement caching in Spring framework?

Caching can be enabled in two ways, using annotation and xml configuration.

We may use @EnableCaching annotation to faciiliate caching.

Below example shows enabling Spring based caching using Annotation.

@Configuration 
@EnableCaching
public class AppConfig { 
}

13. Can a bean class with private constructor be instantiated in Spring framework?

Yes, Spring can invoke private constructors and instantiate object. Spring uses the reflection API to set the bean constructor accessible when it find the constructor with the right arguments, regardless of its visibility.

14. Difference between spring singleton bean and the Gang of Four singleton pattern in Java.

The Gang of Four defines Singleton as having only one instance per ClassLoader whereas Spring singleton is defined as one instance of bean definition per container.

15. How do we inject a null or empty Value in Spring framework?

In Spring, the null and empty value can be injected while creating bean and assigning dependency as described below.

Null value is injected using .

<property name="firstName"><null/></property>

and an empty value can be injected as shown below.

<property name="middleInit" value=""/>

16. What are the different types of events in spring framework?

Spring's ApplicationContext facilitates events and listeners support in spring based applications. We can create beans that listen for events which are published through our ApplicationContext. Event handling in the ApplicationContext is provided through the ApplicationEvent class and ApplicationListener interface. So if a bean implements the ApplicationListener, then every time an ApplicationEvent gets published to the ApplicationContext, that bean is notified.

17. Difference between FileSystemResource and ClassPathResource in Spring framework.

ClassPathResource looks at the class path for spring configuration file while FileSystemResource looks in the file system.

In ClassPathResource spring searches for the spring configuration file at the ClassPath so spring-config.xml should be included in classpath. If spring-config.xml is placed at src folder, then the configuration file can be used directly because src is already in classpath path by default.

In FileSystemResource the path of spring-config.xml (Spring Configuration) file need to be provided relative to the project or the absolute location of the file.

18. Name some of the design patterns used in Spring Framework.

Below are some of the design pattern used in spring framework.

  • Dependency injection Center to the whole BeanFactory / ApplicationContext concepts.
  • Factory pattern BeanFactory for creating instance of an object.
  • Singleton beans defined in spring config files are singletons by default.
  • Template method used extensively to deal with boilerplate repeated code. For example RestTemplate, JmsTemplate, JpaTemplate.
  • Front Controller Spring provides DispatcherServlet to ensure an incoming request gets dispatched to your controllers.
  • View Helper Spring has a number of custom JSP tags, and velocity macros, to assist in separating code from presentation in views.
  • Proxy used in AOP and remoting.
19. Difference between @Bean and @Component annotations in Spring.

@Component auto detects and configure the beans using classpath scanning. There is an implicit one-to-one mapping between the annotated class and the bean (i.e. one bean per class).

@Bean explicitly declares a single bean, rather than letting Spring do it automatically. It decouples the declaration of the bean from the class definition, and lets you create and configure beans exactly how you choose.

20. How do you integrate spring into your Java application?
  • Configure spring dependencies in Maven POM xml.
  • Create application context xml to define beans and its dependencies.
  • Integrate application context xml with web.xml.
  • Deploy and Run the application.
21. How do I get ServletContext and ServletConfig object in a Spring Bean?

Your bean may implement ServletContextAware and ServletConfigAware interfaces and override the setServletContext() and setServletConfig() methods.

@Controller
@RequestMapping(value = "/home")
public class HomeController implements ServletContextAware, ServletConfigAware {

private ServletContext context;
private ServletConfig config;

@Override
public void setServletConfig( ServletConfig servletConfig) {
this.config = servletConfig;

}

@Override
public void setServletContext(ServletContext servletContext) {
this.context = servletContext;
}

}

22. What are the different types of Listener events in Spring?

ContextRefreshedEvent gets called when the context is refreshed or initialized.

RequestHandledEvent gets called when the web context is handling a request.

ContextClosedEvent gets called when the context gets closed.

23. How do I resolve codes to error messages in Spring validation?

MessageCodesResolver resolves the code to error messages. It has the method rejectValue("property name","messages") for example, rejectValue("name", "person.name") that translates error to valid message.

24. Advantages of PropertyEditor in spring.
  • PropertyEditor is used to set the bean properties.
  • PropertyEditor is used to parse HTTP request parameters.
25. Explain the role of ConverterFactory in spring validation.

When there is a need to centralize the conversion logic for an entire class hierarchy, for example, when converting from String to java.lang.Enum objects, implement ConverterFactory.

26. Explain Validator interface in Spring.

Spring features a Validator interface that can be used to validate objects. The Validator interface works with an Errors object so that while validating, validators can report validation failures to the Errors object.

The validation can be applied to any bean by implementing the following two methods of the org.springframework.validation. Validator interface.

supports (Class)- Can Validator validate instances of the supplied Class.

validate (Object, org.springframework.validation.Errors) - validates the given object and in case of validation errors, registers those with the provided Errors object.

27. What happens when a prototype bean is injected into a singleton bean?

Injection happens only once when the Spring context is started. If the bean has prototype scope, Spring will create new prototype bean for every injection. But prototype bean will not be created every time you call its methods or access it from singleton bean.

28. How do you read property files using Spring?

Using PropertyPlaceholderConfigurer, a property resource configuring bean that resolves placeholders in bean property values of context definitions. It pulls values from a properties file into bean definitions.

The default placeholder syntax follows ${...}.

As of Spring 3.1, PropertySourcesPlaceholderConfigurer should be used preferred over this implementation; it is more flexible through taking advantage of the Environment and PropertySource mechanisms also made available in Spring 3.1.

29. Difference between ref bean and ref local attribute in Spring.

ref local requires that the bean being referenced is in the same config file.

Ref bean requires only it to be in the same context or in the parent context.

30. Why is ApplicationContext.getBean considered bad in Spring?

Calling ApplicationContext.getBean() is not Inversion of Control and it basically defeats Spring's purpose as a dependency injection container. Inject dependencies rather than setting it by calling getBean method.

31. How do I remove a spring bean from ApplicationContext?

A spring bean can be removed from context by removing its bean definition.

BeanDefinitionRegistry factory = (BeanDefinitionRegistry) context.getAutowireCapableBeanFactory();

		factory.removeBeanDefinition("mongoRepository");

32. Difference between JDK dynamic proxy and CGLib proxy in Spring.

JDK Dynamic proxy can only proxy by interface so the target class needs to implement an interface, which will also be implemented by the proxy class.

CGLIB can create a proxy by subclassing, so the proxy becomes a subclass of the target class and no need for interfaces.

So Java Dynamic proxies can proxy: public class MyClass implements MyInterface while CGLIB can proxy, public class MyClass itself.

33. What are the limitations for auto-wiring by the constructor in Spring?
  • Only one constructor of any given bean class may carry autowired annotation.
  • Autowired constructor doesn't have to be public.
34. Explain @Configurable annotation in Spring.

@Configurable annotation injects beans into objects of a class whose objects are instantiated using the new operator instead of getting them from the Spring framework.

35. What is the main strategy interface in Spring security?

The main strategy interface for authentication is AuthenticationManager which has only one method.

public interface AuthenticationManager {

  Authentication authenticate(Authentication authentication)
    throws AuthenticationException;

}

36. How to logout the session in spring security?

To logout the session, use j_spring_security_logout as action.

<a href="j_spring_security_logout">logout.</a>
 
37. How does Prototype scope work in spring?

Whenever you call for an instance of the prototype scoped bean, Spring will create a new instance and return it. This differs from the default singleton scope, where a single object instance is instantiated once per Spring IoC container.

38. Can you use @Autowired annotation with static field members?

It is not recommended, so refrain from autowiring static fields.

39. Mention the key interface in that abstracts Spring framework transactions.

org.springframework.transaction.PlatformTransactionManager.

40. How to load spring beans from the dependency jar in my project?

To load the annotated beans from the dependent jar, mention the fully qualified package name in @ComponentScan of your project.

@ComponentScan(basePackages = {"net.javapedia.from.jar"})
41. Explain @Configuration annotation in Spring.

The @Configuration annotation indicates that a class declares one or more @Bean methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime.

@Configuration
public class AppConfig {

    @Bean(name="exampleService")
    public ExampleClass service() 
    {
       ...
    }
}

42. What is the difference between @Configuration and @Component in spring?

@Configuration Indicates that a class declares one or more @Bean methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime.

@Component Indicates that an annotated class is a "component". Such classes are considered as candidates for auto-detection when using annotation-based configuration and classpath scanning.

@Configuration is also a @Component as it is meta-annotated with @Component, so @Configuration classes are eligible for component scanning.

43. Difference between @Bean and @Component annotation in spring.

Both aim to register target type in Spring container.

@Component auto scan and detects which configures the beans using classpath scanning while @Bean explicitly declares a single bean, rather than letting Spring do it automatically.

@Component does not decouple the declaration of the bean from the class definition where as @Bean decouples the declaration of the bean from the class definition.

@Bean is applicable to methods, whereas @Component is applicable to types.

@Component is a class level annotation where as @Bean is a method level annotation and name of the method serves as the bean name.

@Component need NOT use @Configuration annotation while @Bean annotation has to be used within the class annotated with @Configuration.

@Component has its specializations such as @Controller, @Repository and @Service while @Bean has no such specializations.

44. Explain fixedDelay and fixedRate properties in Spring @Scheduled Annotation.

We can run scheduled tasks using Spring @Scheduled annotation however the properties fixedDelay and fixedRate determines the nature of execution.

The fixedDelay execute the annotated method with a fixed period in milliseconds between the end of the last invocation and the start of the next.

The fixedRate property execute the annotated method with a fixed period in milliseconds between invocations.

@Component
public class ScheduledService {

    int i=0;
    @Scheduled(fixedDelay = 2000) //in ms
    public void myFixedDelayScheduledMethod() {
        i++;
        System.out.println ("Running scheduled Task, iteration :"+ i  + " Thread name: "+ Thread.currentThread().getName()) ;
    }


    @Scheduled(fixedRate = 4000) //in ms
    public void myFixedRateScheduledMethod() {
        System.out.println ("Running fixedRate Task, Thread name: "+Thread.currentThread().getName());
    }
}

45. What is Spring SSE?

Spring Server-Sent-Events (SSE) is an HTTP standard that allows a web application to handle a unidirectional event stream and receive updates whenever server emits data.

WebSockets offer full-duplex (2 way) communication between the server and the client, while SSE uses uni-directional communication.

46. Advantages of SSE over Websockets.

  • SSE is transported over simple HTTP instead of a custom protocol.
  • SSE can be poly-filled with javascript to "backport" SSE to browsers that do not support it yet.
  • SSE has built in support for re-connection and event-id.
  • Simpler protocol.
  • SSE has no trouble with corporate firewalls doing packet inspection.

47. Advantages of Websockets over SSE.

Websockets provide Real-time, bi-directional (2 way) communication while SSE is one-way. Websocket has native support in most browsers.

«
»
Spring batch Interview questions

Comments & Discussions