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.

1. Differentiate commandName and modelAttribute.

Both are similar and has no difference.

Read full answer

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) { retur...

Read full answer

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...

Read full answer

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 framew...

Read full answer

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. defaultHtmlEscape true For all forms on a given JSP page,

Read full answer

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

The tag has access to the underlying model and binding results, so on error, it can use another style class. 

Read full answer

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, Read full answer

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 HT...

Read full answer

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 annotati...

Read full answer

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 getSessio...

Read full answer

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...

Read full answer

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 { }

Read full answer

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.

Read full answer

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.

Read full answer

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 . and an empty value can be injected as shown below.

Read full answer

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 Application...

Read full answer

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 a...

Read full answer

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 met...

Read full answer

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 declarati...

Read full answer

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.

Read full answer

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...

Read full answer

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.

Read full answer

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.

Read full answer

24. Advantages of PropertyEditor in spring.

PropertyEditor is used to set the bean properties. PropertyEditor is used to parse HTTP request parameters.

Read full answer

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.

Read full answer

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 met...

Read full answer

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.

Read full answer

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, PropertySourcesPlaceh...

Read full answer

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.

Read full answer

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.

Read full answer

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");

Read full answer

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 ca...

Read full answer

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 .

Read full answer

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.

Read full answer

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; }

Read full answer

36. How to logout the session in spring security?

To logout the session, use j_spring_security_logout as action. logout.

Read full answer

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.

Read full answer

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

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

Read full answer

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

org.springframework.transaction.PlatformTransactionManager .

Read full answer

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"})

Read full answer

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 Exampl...

Read full answer

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 candida...

Read full answer

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 ...

Read full answer

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 f...

Read full answer

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 communicat...

Read full answer

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 in...

Read full answer

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.

Read full answer

«
»

Comments & Discussions