Spring / Spring Interview questions II
Both are similar and has no difference.
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(); }
@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.
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.
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" />
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" />
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"/>
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 (&lt;) and ampersand (&amp;) must be escaped before using them in HTML.
@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 { }
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.
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.
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 { }
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.
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.
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=""/>
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.
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.
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.
@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.
- 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.
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; } }
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.
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.
- PropertyEditor is used to set the bean properties.
- PropertyEditor is used to parse HTTP request parameters.
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.
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.
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.
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.
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.
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.
A spring bean can be removed from context by removing its bean definition.
BeanDefinitionRegistry factory = (BeanDefinitionRegistry) context.getAutowireCapableBeanFactory(); factory.removeBeanDefinition("mongoRepository");
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.
- Only one constructor of any given bean class may carry autowired annotation.
- Autowired constructor doesn't have to be public.
@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.
The main strategy interface for authentication is AuthenticationManager which has only one method.
public interface AuthenticationManager { Authentication authenticate(Authentication authentication) throws AuthenticationException; }
To logout the session, use j_spring_security_logout as action.
<a href="j_spring_security_logout">logout.</a>
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.
It is not recommended, so refrain from autowiring static fields.
org.springframework.transaction.PlatformTransactionManager
.
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"})
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() { ... } }
@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.
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.
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()); } }
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.
- 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.
Websockets provide Real-time, bi-directional (2 way) communication while SSE is one-way. Websocket has native support in most browsers.