Spring, Spring MVC Interview Questions : Part 1 | Code Factory


Donate : Link

Medium Blog : Link

Applications : Link

Spring Framework – Architecture

DispatcherServlet Diagram

1. difference between Spring, Spring MVC and Spring Boot.

Spring: Spring Framework is the most popular application development framework of Java. The main feature of the Spring Framework is dependency Injection or Inversion of Control (IoC). With the help of Spring Framework, we can develop a loosely coupled application.

Spring MVC: Spring MVC is a Web MVC Framework for building web applications. It contains a lot of configuration files for various capabilities. It is an HTTP oriented web application development framework.

Spring Boot: Spring Boot is a module of Spring Framework. It allows us to build a stand-alone application with minimal or zero configurations. It is better to use if we want to develop a simple Spring-based application or RESTful services. Spring Boot makes it easy to quickly bootstrap and start developing a Spring-based application. It avoids a lot of boilerplate code. It hides a lot of complexity behind the scene so that the developer can quickly get started and develop Spring-based applications easily.

Spring VS Spring Boot:

SpringSpring Boot
Spring Framework is a widely used Java EE framework for building applications.Spring Boot Framework is widely used to develop REST APIs.
It aims to simplify Java EE development that makes developers more productive.It aims to shorten the code length and provide the easiest way to develop Web Applications.
The primary feature of the Spring Framework is dependency injection.The primary feature of Spring Boot is Autoconfiguration. It automatically configures the classes based on the requirement.
It helps to make things simpler by allowing us to develop loosely coupled applications.It helps to create a stand-alone application with less configuration.
The developer writes a lot of code (boilerplate code) to do the minimal task.It reduces boilerplate code.
To test the Spring project, we need to set up the sever explicitly.Spring Boot offers embedded server such as Jetty and Tomcat, etc.
It does not provide support for an in-memory database.It offers several plugins for working with an embedded and in-memory database such as H2.
Developers manually define dependencies for the Spring project in pom.xml.Spring Boot comes with the concept of starter in pom.xml file that internally takes care of downloading the dependencies JARs based on Spring Boot Requirement.

Spring MVC VS Spring Boot:

Spring MVCSpring Boot
Spring MVC is a model view controller-based web framework under the Spring framework.Spring Boot is a module of Spring for packaging the Spring-based application with sensible defaults.
It provides ready to use features for building a web application.It provides default configurations to build Spring-powered framework.
It requires build configuration manually.There is no need to build configuration manually.
A Deployment descriptor is required.There is no requirement for a deployment descriptor.
It specifies each dependency separately.It avoids boilerplate code and wraps dependencies together in a single unit.
It takes more time to achieve the same.It reduces development time and increases productivity.

3. How Spring is lightweight

  • * To get capabilities of Servlet we must have to implement Servlet inteface or extend servlet classes. But in case of Spring they are not force to implement any interface or any classes. If you require Spring feature, instead of implementing interfaces and extending classes you can take here class reference as a associated reference. By associate them we can get B and C class behaviour, Spring recommending us associate instead of inheritance, they are recommending has-a relationship. Then your class became light weight. Use associate model instead of using extending model your class will became light weight.
interface A {
	// lets say this is Spring interface
}

class B {
	// lets say this is Spring class
}

class C {
	// lets say this is Spring class
}

class D {
	// normal class
	B b = new B();
	C c = new C();
	OR
	B b;
	C c;
}
  • Spring calls itself ‘lightweight’ because you don’t need all of Spring to use part of it. For example, you can use Spring JDBC without Spring MVC.
  • Spring provides various modules for different purposes; you can just inject dependencies according to your required module. That is, you don’t need to download or inject all dependencies or all JARs to use a particular module.
enter image description here

4. AOP (Aspect Oriented Programming)

  • In computing, aspect-oriented programming (AOP) is a programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns.

5. Cross cutting in Java.

  • The crosscutting concern is a concern which is applicable throughout the application and it affects the entire application. For example: logging, security and data transfer are the concerns which are needed in almost every module of an application, hence they are cross-cutting concerns.

6. What is a resource bundle?

  • The ResourceBundle class is used to internationalize the messages. In other words, we can say that it provides a mechanism to globalize the messages.
  • The hardcoded message is not considered good in terms of programming, because it differs from one country to another. So we use the ResourceBundle class to globalize the massages. The ResourceBundle class loads these information from the properties file that contains the messages.

7. Dependency Injection and Inversion of Control (IoC)

Inversion of Control (IoC):

Definition of IoC: “IoC is when you have someone else create objects for you.” So instead of writing “new MyObject” in your code, the object is created by someone else. This ‘someone else’ is normally referred to as an IoC container.

This simple explanation illustrates some very important ideas:

  1. It is called IoC because control of the object is inverted. It is not the programmer, but someone else who controls the object.
  2. IoC is relative in the sense that it only applies to some objects of the application. So there may be IoC for some objects, whereas others are under the direct control of the programmer.

Quick summary of the ideas:

  1. IoC containers control and manage the lifecycle of some objects: creation, destruction, and callback invocations.
  2. The programmer must identify the classes whose instances are to be managed by the IoC container. There are several ways to do this: with annotations, by extending some specific classes, using external configuration.
  3. The programmer can influence, to some extent, the way the objects are managed by the IoC container. Normally, this is achieved by overriding the default behavior of the object callbacks.

Dependency Injection:

  • * Dependency Injection is a fundamental aspect of the Spring framework, through which the Spring container “injects” objects into other objects or “dependencies”.
  • * Simply put, this allows for loose coupling of components and moves the responsibility of managing components onto the container.

Having DI is the opposite to having hardcoded dependencies.

//Hardcoded dependency
public class MyClass { 
    private MyDependency myDependency = new MyDependency(); 
}

//Injected dependency
public class MyClass { 
    private MyDependency myDependency;
    public MyClass(MyDependency myDependency){
        this.myDependency = myDependency;
    }
}

A dependency can be injected in several ways, like a parameter in the constructor or through a “set” method.

As important as DI is, there is a downside to its use, namely: management of dependencies is inconvenient. Let’s take a look at an example: MyClass1 depends on MyClass2, that in turns depends upon MyClass3:

public class MyClass3 {
    public void doSomething(){}
}

//MyClass2 depends on MyClass3
public class MyClass2 {
    private MyClass3 myClass3;

    public MyClass2(MyClass3 myClass3){
        this.myClass3 = myClass3;
    }

    public void doSomething(){
        myClass3.doSomething();
    }
}

//MyClass1 depends on MyClass2
public class MyClass1 {
    private MyClass2 myClass2;

    public MyClass1(MyClass2 myClass2){
        this.myClass2 = myClass2;
    }

    public void doSomething(){
        myClass2.doSomething();
    }
}

public class Main {
    public static void main(String[] args) {
        //All dependencies need to be managed by the developer
        MyClass3 myClass3 = new MyClass3();
        MyClass2 myClass2 = new MyClass2(myClass3);
        MyClass1 myClass1 = new MyClass1(myClass2);
        myClass1.doSomething();
    }
}

Now, let’s assume that further down the line, MyClass2 needs a new dependency: MyClass4. We need to make changes to account for this new dependency:

public class MyClass2 {
    private MyClass3 myClass3;
    private MyClass4 myClass4;

    public MyClass2(MyClass3 myClass3, MyClass4 myClass4){
        this.myClass3 = myClass3;
        this.myClass4 = myClass4;
    }

    public void doSomething(){
        myClass3.doSomething();
        myClass4.doSomething();
    }
}

public class Main {
    public static void main(String[] args) {
        MyClass4 myClass4 = new MyClass4();
        MyClass3 myClass3 = new MyClass3();
        MyClass2 myClass2 = new MyClass2(myClass3, myClass4);
        MyClass1 myClass1 = new MyClass1(myClass2);
        myClass1.doSomething();
    }
}

Although the situation described in this example is not too bad, real-life applications can have hundreds of dependencies scattered all across the codebase whose creation and management would need to be centralized like in the above example.

Inversion of Control and Dependency Injection Playing Together:

We just discussed the issue of managing hundreds of dependencies in a real-life application, possibly with very complicated dependency graphs.

So here is where IoC comes to the rescue. With IoC, the dependencies are managed by the container, and the programmer is relieved of that burden.

Using annotations like @Autowired, the container is asked to inject a dependency where it is needed, and the programmers do not need to create/manage those dependencies by themselves.

public class MyClass1 {

    @Autowired
    private MyClass2 myClass2;

    public void doSomething(){
        myClass2.doSomething();
    }
}

public class MyClass2 {

    @Autowired
    private MyClass3 myClass3;

    @Autowired
    private MyClass4 myClass4;

    public void doSomething(){
        myClass3.doSomething();
        myClass4.doSomething();
    }
}

8. Can we have multiple DispatcherServlet spring application.

  • We can have to multiple Dispatcher Servlets, like we can have 2(or more) DispatcherServlet with 2( or more) servlets name.So the D1 and D2 could map to different URL path.
  • Example:- (both block’s code in web.xml)
<!-- configured by WEB-INF/mac-servlet.xml -->
<servlet>
    <servlet-name>mac</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<!-- configured by WEB-INF/windows-servlet.xml -->
<servlet>
        <servlet-name>windows</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
</servlet>

URL path could be mapped like :-

<servlet-mapping>
    <servlet-name>mac</servlet-name>
    <url-pattern>/mac/*</url-pattern>
</servlet-mapping>

<servlet-mapping>
    <servlet-name>windows</servlet-name>
    <url-pattern>/windows/*</url-pattern>
</servlet-mapping>

Spring Boot with multiple DispatcherServlet

test.foo.
FooConfig.java
FooController.java
test.bar.
BarConfig.java
BarController.java
test.app.
Application.java
MyService.java
src/main/resources/application.properties

Application.java

@SpringBootApplication(exclude=DispatcherServletAutoConfiguration.class)
public class Application {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }
    @Bean
    public ServletRegistrationBean foo() {
        DispatcherServlet dispatcherServlet = new DispatcherServlet();   
        AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
        applicationContext.register(FooConfig.class);
        dispatcherServlet.setApplicationContext(applicationContext);
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(dispatcherServlet, "/foo/*");
        servletRegistrationBean.setName("foo");
        return servletRegistrationBean;
    }
    @Bean
    public ServletRegistrationBean bar() {
        DispatcherServlet dispatcherServlet = new DispatcherServlet();
        AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
        applicationContext.register(BarConfig.class);
        dispatcherServlet.setApplicationContext(applicationContext);
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(dispatcherServlet, "/bar/*");
        servletRegistrationBean.setName("bar");
        return servletRegistrationBean;
    }
}
  • The exclude does prevent Spring Boot from creating its own DispatcherServlet with / mapping. You can remove that line, if you want that mapping or define your own.
  • You can add servletRegistrationBean.setLoadOnStartup(1) if you want to have your Servlets initialized on application start. Else it will wait for the first request for that servlet.
  • It’s important to set servletRegistrationBean.setName(...), else the servlets will override each other.

FooConfig.java & BarConfig.java:

@Configuration @ComponentScan @EnableWebMvc
public class FooConfig { }
  • @EnableWebMvc will enable the component scan. Without it, it won’t find the @Controller class.

The Controller and Service code is not important. You just have to know, that if you have @RequestMapping("/foo") inside FooController, the request must be GET /foo/foo because the Servlet’s URL mapping is /foo/*. It’s not possible to call the URL GET /foo because the Servlet URL mapping needs a / at the end of its path (in other words: GET /foo will look for a Servlet with / mapping!), though @RequestMapping("") must be called via GET /foo/. And of course it was not possible to use /foo or /foo* as Servlet mapping (or I just did not find the correct settings for that)

Scope: The Controllers can’t see each other, though it’s not possible to @Autowired them in each other. Also the Service can’t @Autowired any of the Controllers. But the Controllers can @Autowired the Service.

9. Spring DispatcherServlet

  • https://howtodoinjava.com/spring5/webmvc/spring-dispatcherservlet-tutorial/
  • DispatcherServlet acts as front controller for Spring based web applications. It provides a mechanism for request processing where actual work is performed by configurable, delegate components. It is inherited from javax.servlet.http.HttpServlet, it is typically configured in the web.xml file.
  • A web application can define any number of DispatcherServlet instances. Each servlet will operate in its own namespace, loading its own application context with mappings, handlers, etc. Only the root application context as loaded by ContextLoaderListener, if any, will be shared. In most cases, applications have only single DispatcherServlet with the context-root URL(/), that is, all requests coming to that domain will be handled by it.
  • DispatcherServlet uses Spring configuration classes to discover the delegate components it needs for request mapping, view resolution, exception handling etc.

10. What is difference between @Repository, @Service, @Controller and @Component?

https://javarevisited.blogspot.com/2017/11/difference-between-component-service.html

* https://medium.com/@sendvjs/difference-between-component-service-controller-and-repository-in-spring-5f9fa05bcb1d

  1. @Component is a universal stereotype for any Spring-managed component or bean.
  2. @Repository is a stereotype for the persistence layer.
  3. @Service is a stereotype for the service layer.
  4. @Controller is a stereotype for the presentation layer (spring-MVC).
image
  • Their only difference comes in their purpose i.e. @Controller is used in Spring MVC to define controller, which are first Spring bean and then the controller. Similarly, @Service is used to annotated classes that hold business logic in the Service layer and @Repository is used in the Data Access layer.
  • By using @Controller annotation we do two things, first, we declare that this class is a Spring bean and should be created and maintained by Spring ApplicationContext, but also we indicate that its a controller in MVC setup. This latter property is used by web-specific tools and functionalities.
  • * For example, DispatcherServlet will look for @RequestMapping on classes that are annotated using @Controller but not with @Component.
  • This means @Component and @Controller are the same with respect to bean creation and dependency injection but later is a specialized form of former. Even if you replace @Controller annotation with @Component, Spring can automatically detect and register the controller class but it may not work as you expect with respect to request mapping.
  • The same is true for @Service and @Repository annotation, they are a specialization of @Component in service and persistence layer. A Spring bean in the service layer should be annotated using @Service instead of @Component annotation and a spring bean in the persistence layer should be annotated with @Repository annotation.
  • @Repository’s not only helping in annotation based configure but also catch Platform-specific exceptions and re-throw them as one of Spring’s unified unchecked exception.

12. @Bean annotation

  • * In Spring, the objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. Otherwise, a bean is simply one of many objects in your application. Beans, and the dependencies among them, are reflected in the configuration metadata used by a container.
@Bean(name="fullSpot")
 // Not mandatory. If not specified, it takes the method name i.e., "fullSpotField" as qualifier name.
public FieldDescriptor fullSpotField() {
    FieldDescriptor ans = new FieldDescriptor("full_spot", String.class);
    return ans;
}

@Bean("annotationIdSpot")
// Same as above comment.
public FieldDescriptor annotationIdField() {
    FieldDescriptor ans = new FieldDescriptor("annotationID", Integer.class);
    return ans;
}

... AND ...

@Autowired
@Qualifier("fullSpot")
public FieldDescriptor fullSpotField;

@Autowired
@Qualifier("annotationIdSpot")
public FieldDescriptor annotationIdField;

13. @Scope (Bean Scope)

@Bean
@Scope("prototype")
... OR ...
@Bean
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
  1. singleton – This scopes the bean definition to a single instance per Spring IoC container (default).
  2. prototype – This scopes a single bean definition to have any number of object instances.
  3. request – This scopes a bean definition to an HTTP request. Only valid in the context of a web-aware Spring ApplicationContext.
  4. session – This scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
  5. global-session – This scopes a bean definition to a global HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.

14. @Autowire annotation

  • Spring allows initialization of the object though annotations and/or xml bean definitions. In earlier version of the spring there was a need to write all the beans in an xml file. For eg.

spring-context.xml

<bean id="transport"     class="com.Transport"> 
      <property name="vehicle" ref="vehicle"> 
 </bean> 
<bean id="vehicle" class="com.Car"></bean>
  • Here Vehicle is an interface and Car is an Implementation of Vehicle.
  • With many beans in project, this process became tedious. So then in later version Spring introduced annotation based wiring using @Autowired annotation. This needs to be placed directly in Java file just above member defintion. This member is an interface member. Spring automatically then would initialize this member with the object of the implementor of this interface. If there are multiple implementations then qualifier attribute can be added to autowired annotation. No need to define these dependencies through xml. Eg.
Class Transport{ 
  
  @Autowired 
  @Qualifier("car")  
  Public Vehicle v; 
  ......  
 
}

Autowiring Modes:

  1. no: No autowiring at all. Bean references must be defined via a ref element.
  2. byName: This option enables the dependency injection based on bean names. When autowiring a property in bean, property name is used for searching a matching bean definition in configuration file. If such bean is found, it is injected in property. If no such bean is found, a error is raised.
  3. byType: This option enables the dependency injection based on bean types. When autowiring a property in bean, property’s class type is used for searching a matching bean definition in configuration file. If such bean is found, it is injected in property. If no such bean is found, a error is raised.
  4. constructor: Autowiring by constructor is similar to byType, but applies to constructor arguments. In autowire enabled bean, it will look for class type of constructor arguments, and then do a autowire bytype on all constructor arguments. Please note that if there isn’t exactly one bean of the constructor argument type in the container, a fatal error is raised.

@Autowired on properties

  • When @Autowired is used on properties, it is equivalent to autowiring by ‘byType‘ in configuration file.
public class EmployeeBean
{
    @Autowired
    private DepartmentBean departmentBean;
 
    public DepartmentBean getDepartmentBean() {
        return departmentBean;
    }
    public void setDepartmentBean(DepartmentBean departmentBean) {
        this.departmentBean = departmentBean;
    }
    //More code
}

@Autowired on property setters

When @Autowired is used on setters, it is also equivalent to autowiring by ‘byType‘ in configuration file.

public class EmployeeBean
{
    private DepartmentBean departmentBean;
 
    public DepartmentBean getDepartmentBean() {
        return departmentBean;
    }
 
    @Autowired
    public void setDepartmentBean(DepartmentBean departmentBean) {
        this.departmentBean = departmentBean;
    }
    //More code
}

@Autowired on constructors

When @Autowired is used on bean’s constructor, it is also equivalent to autowiring by ‘constructor‘ in configuration file.

public class EmployeeBean
{
    @Autowired
    public EmployeeBean(DepartmentBean departmentBean)
    {
        this.departmentBean = departmentBean;
    }
 
    private DepartmentBean departmentBean;
 
    public DepartmentBean getDepartmentBean() {
        return departmentBean;
    }
    public void setDepartmentBean(DepartmentBean departmentBean) {
        this.departmentBean = departmentBean;
    }
    //More code
}

15. @Qualifier @Primary annotation

  • The @Autowired annotation is a great way of making the need to inject a dependency in Spring explicit. And although it’s useful, there are use cases for which this annotation alone isn’t enough for Spring to understand which bean to inject.
  • By default, Spring resolves autowired entries by type.
  • If more than one bean of the same type is available in the container, the framework will throw NoUniqueBeanDefinitionException, indicating that more than one bean is available for autowiring.
  • Let’s imagine a situation in which two possible candidates exist for Spring to inject as bean collaborators in a given instance:
@Component("fooFormatter")
public class FooFormatter implements Formatter {
 
    public String format() {
        return "foo";
    }
}
 
@Component("barFormatter")
public class BarFormatter implements Formatter {
 
    public String format() {
        return "bar";
    }
}
 
@Component
public class FooService {
     
    @Autowired
    private Formatter formatter;
}
  • If we try to load FooService into our context, the Spring framework will throw a NoUniqueBeanDefinitionException. This is because Spring doesn’t know which bean to inject. To avoid this problem, there are several solutions. The @Qualifier annotation is one of them.

@Qualifier Annotation

By using the @Qualifier annotation, we can eliminate the issue of which bean needs to be injected.

public class FooService {
     
    @Autowired
    @Qualifier("fooFormatter")
    private Formatter formatter;
}
  • By including the @Qualifier annotation together with the name of the specific implementation we want to use – in this example, Foo – we can avoid ambiguity when Spring finds multiple beans of the same type.

@Qualifier vs @Primary

  • This annotation defines a preference when multiple beans of the same type are present. The bean associated with the @Primary annotation will be used unless otherwise indicated.
@Configuration
public class Config {
 
    @Bean
    public Employee johnEmployee() {
        return new Employee("John");
    }
 
    @Bean
    @Primary
    public Employee tonyEmployee() {
        return new Employee("Tony");
    }
}
  • In this example, both methods return the same Employee type. The bean that Spring will inject is the one returned by the method tonyEmployee. This is because it contains the @Primary annotation. This annotation is useful when we want to specify which bean of a certain type should be injected by default.
  • if both the @Qualifier and @Primary annotations are present, then the @Qualifier annotation will have precedence.
  • Basically, @Primary defines a default, while @Qualifier is very specific.

18. @Cacheable, @CacheEvict and @CachePut

@Cacheable

  • The simplest way to enable caching behavior for a method is to demarcate it with @Cacheable and parameterize it with the name of the cache where the results would be stored:
@Cacheable("addresses")
public String getAddress(Customer customer) {...}
  • The getAddress() call will first check the cache addresses before actually invoking the method and then caching the result.
  • While in most cases, one cache is enough, the Spring framework also supports multiple caches to be passed as parameters:
@Cacheable({"addresses", "directory"})
public String getAddress(Customer customer) {...}
  • In this case, if any of the caches contains the required result, the result is returned and the method is not invoked.

@CacheEvict

  • The problem is size – we don’t want to populate the cache with values that we don’t need often. Caches can grow quite large, quite fast, and we could be holding on to a lot of stale or unused data.
  • The @CacheEvict annotation is used to indicate the removal of one or more/all values – so that fresh values can be loaded into the cache again:
@CacheEvict(value="addresses", allEntries=true)
public String getAddress(Customer customer) {...}
  • Here, we’re using the additional parameter allEntries in conjunction with the cache to be emptied – to clear all the entries in the cache addresses and prepare it for new data.

@CachePut

  • With the @CachePut annotation, you can update the content of the cache without interfering the method execution. That is, the method would always be executed and the result cached.
@CachePut(value="addresses")
public String getAddress(Customer customer) {...}
  • The difference between @Cacheable and @CachePut is that @Cacheable will skip running the method, whereas @CachePut will actually run the method and then put its results in the cache.

19. Cross Origin

@RequestMapping(value = "/products")
@CrossOrigin(origins = "http://localhost:7070")
public ResponseEntity<Object> getProduct() {
   return null;
}

20. How do you call a Stored Procedure using Jpa, Hibernate or Jdbc?

Using Jpa:

https://34codefactory.wordpress.com/2019/11/02/stored-procedures-with-spring-boot-jpa-code-factory/

Employee.java

@Entity
@Table(name = "employee")
@NamedStoredProcedureQueries({
	@NamedStoredProcedureQuery(
		name = "findEmpById",
		procedureName = "FIND_EMP_BY_ID",
		resultClasses = {Employee.class},
		parameters = {
			@StoredProcedureParameter(
				name = "p_id",
				type = Integer.class,
				mode = ParameterMode.IN
			)
		}
	)
})
public class Employee {
    ...
}

EmployeeRepositoryImpl.java

@PersistenceContext
EntityManager em;

@Override
public Employee findEmpById(int p_id) {
	StoredProcedureQuery query = em.createNamedStoredProcedureQuery("findEmpById").setParameter("p_id", p_id);
	return (Employee) query.getResultList().get(0);
}

Using Hibernate:

https://34codefactory.wordpress.com/2019/11/04/call-stored-procedures-using-spring-boot-hibernate-code-factory/

Employee.java

@Entity
@Table(name = "employee")
@NamedNativeQueries({
	@NamedNativeQuery(
		name = "findEmpById",
		query = "CALL FIND_EMP_BY_ID(:p_id)",
		resultClass = Employee.class
	)
})
@NamedStoredProcedureQueries({
	@NamedStoredProcedureQuery(
		name = "findEmpById",
		procedureName = "FIND_EMP_BY_ID",
		resultClasses = {Employee.class},
		parameters = {
			@StoredProcedureParameter(
				name = "p_id",
				type = Integer.class,
				mode = ParameterMode.IN
			)
		}
	)
})
public class Employee {
    ...
}

EmployeeService.java

@Service
public class EmployeeService {

	@Autowired
	SessionFactory sessionFactory;
	
	@PersistenceContext
	EntityManager em;
	
	public Employee namedNativeQuery(int id) {
		Session session = sessionFactory.openSession();
		Query query = session.getNamedQuery("findEmpById").setParameter("p_id", id);
		return (Employee) query.list().get(0);
	}

	public Employee namedStoredProcedureQuery(int id) {
		StoredProcedureQuery query = em.createNamedStoredProcedureQuery("findEmpById").setParameter("p_id", id);
		return (Employee) query.getResultList().get(0);
	}
}

Using Jdbc:

CallableStatement stmt=con.prepareCall("{call insertR(?,?)}");  
stmt.setInt(1,1011);  
stmt.setString(2,"Amit");  
stmt.execute();

21. Difference between filter and interceptor in java

Filter:

A filter as the name suggests is a Java class executed by the servlet container for each incoming http request and for each http response. This way, is possible to manage HTTP incoming requests before them reach the resource, such as a JSP page, a servlet or a simple static page; in the same way is possible to manage HTTP outbound response after resource execution.

This behaviour allow to implement common functionality reused in many different contexts.

Filter

As shown in the figure above, the filter runs in the web container so its definition will also be contained in the web.xml file. In the case of the ListFeeds project one of main filter is the CORS management:

<filter>
    <filter-name>CORSFilter</filter-name>
    <filter-class>com.listfeeds.components.CORSFilter</filter-class>
    <init-param>
        <param-name>fake-param</param-name>
        <param-value>fake-param-value</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CORSFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

In the filter definition the filter implemented by the class com.listfeeds.filters.CORSFilter with the all endpoints that satisfy the expression: /* (in this case all)

public class CORSFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        ...
        ...
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

}

The filer include three main methods:

  • init: executed to initialize filter using init-param element in filter definition
  • doFilter: executed for all HTTP incoming request that satisfy “url-pattern”
  • release resources used by the filter

Interceptor:

Spring Interceptors are similar to Servlet Filters but they acts in Spring Context so are many powerful to manage HTTP Request and Response but they can implement more sofisticated behaviour because can access to all Spring context.

Spring Interceptor

The Spring interceptor are execute in SpringMVC context so they have be defined in rest-servlet.xml file:

<mvc:interceptors>
    <bean class="com.listfeeds.interceptors.LogContextInterceptor" />
    <bean class="com.listfeeds.interceptors.TimedInterceptor" />
</mvc:interceptors>
LogContextInterceptor.java
public class LogContextInterceptor extends HandlerInterceptorAdapter {

    @Override
    public void afterCompletion(
            HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

        ...
        ...
    }

    @Override
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws Exception {

        ...
        return true OR false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

        ...
        ...
    }
}

The interceptor include three main methods:

  • preHandle: executed before the execution of the target resource
  • afterCompletion: executed after the execution of the target resource (after rendering the view)
  • posttHandle: Intercept the execution of a handler

22. * Advantage of Spring Data JPA over Hibernate?

  • JPA: Java persistence api which provide specification for persisting, reading, managing data from your java object to relations in database.
  • Hibernate: There are various provider which implement jpa. Hibernate is one of them. So we have other provider as well. But if using jpa with spring it allows you to switch to different providers in future.
  • Spring Data JPA: This is another layer on top of jpa which spring provide to make your life easy.
  • Let’s say you are using spring + hibernate for your application. Now you need to have dao interface and implementation where you will be writing crud operation using SessionFactory of hibernate. Let say you are writing dao class for Employee class, tomorrow in your application you might need to write similiar crud operation for any other entity. So there is lot of boilerplate code we can see here.
  • Now Spring data jpa allow us to define dao interfaces by extending its repositories (crudrepository, jparepository) so it provide you dao implementation at runtime. You don’t need to write dao implementation anymore. Thats how spring data jpa makes your life easy.

23. Difference Between @Component and @Bean

  1. @Component was introduced in spring 2.5 and @Bean was introduced in spring 3.0.
  2. @Component auto detects and configures the beans using classpath scanning whereas @Bean explicitly declares a single bean, rather than letting Spring do it automatically.
  3. @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.
  4. @Component is a class level annotation whereas @Bean is a method level annotation and name of the method serves as the bean name.
  5. @Component need not to be used with the @Configuration annotation where as @Bean annotation has to be used within the class which is annotated with @Configuration.
  6. We cannot create a bean of a class using @Component, if the class is outside spring container whereas we can create a bean of a class using @Bean even if the class is present outside the spring container.
  7. @Component has different specializations like @Controller, @Repository and @Service whereas @Bean has no specializations.

25. What is the difference between Model, ModelMap and ModelAndView?

  • Model is an interface. Since 2.5
  • Java-5-specific interface that defines a holder for model attributes. Primarily designed for adding attributes to the model. Allows for accessing the overall model as a java.util.Map.
@RequestMapping(method = RequestMethod.GET)
public String printHello(Model model) {
    model.addAttribute("message", "Hello World!!");
    return "hello";
}
  • ModelMap is a class. Since 2.0
  • ModelMap class is basically a LinkedHashMap. It add some methods for convenience. Just like the Model interface above, ModelMap is also used to pass values to render a view.
  • We can use methods and functionality of LinkedHashMap, HashMap, AbstractMap, Object, Map in ModelMap.
@RequestMapping("/helloworld")
public String hello(ModelMap map) {
    String helloWorldMessage = "Hello world!";
    String welcomeMessage = "Welcome!";
    map.addAttribute("helloMessage", helloWorldMessage);
    map.addAttribute("welcomeMessage", welcomeMessage);
    return "hello";
}
  • ModelAndView is just a container for both a ModelMap and a View object. It allows a controller to return both as a single value.
@RequestMapping("/welcome")
public ModelAndView helloWorld() {
    String message = "Hello World!";
    return new ModelAndView("welcome", "message", message);
}

26. What is the difference between model.put() and model.addAttribute()?

  • Code for addAttribute method is listed below. It does an additional null check before calling a put.
  • addAttribute() returns the ModelMap back. So, you can chain calls.
  • model.addAttribute(“attribute1”,”value1”).addAttribute(“attribute2”,”value2”);
  • put() method of Map return the previous value associated with key, or null if there was no mapping for key (A null return can also indicate that the map previously associated null with key).
/**
 * Add the supplied attribute under the supplied name.
 * @param attributeName the name of the model attribute (never {@code null})
 * @param attributeValue the model attribute value (can be {@code null})
 */
public ModelMap addAttribute(String attributeName, @Nullable Object attributeValue) {
	Assert.notNull(attributeName, "Model attribute name must not be null");
	put(attributeName, attributeValue);
	return this;
}

27. How @ComponentScan works in Spring or SpringBoot?

  • If your other package hierarchies are below your main app with the @SpringBootApplication annotation, you’re covered by the implicit Component Scan.
  • If there are beans/components in other packages that are not sub-packages of the main package, you should manually add them as @ComponentScan
  • @SpringBootApplication is defined in the SpringDemo class which is in the package com.codeFactory.example
  • @SpringBootApplication defines an automatic Component Scan on the package com.codeFactory.example.
  • You are fine if all your components are defined in the above package or a sub-package of it.
  • However, let’s say one of the components is defined in package com.codeFactory.test
  • In this case, you would need to add the new package into Component Scan.
  • You have two options:
  • Define @ComponentScan("com.codeFactory")
    • This would scan the entire parent tree of com.codeFactory.
  • Or define two specific Component Scans by using an array.
    • @ComponentScan({"com.codeFactory.example","com.codeFactory.test"})

28. @Controller and @RestController Annotations.

  • @Controller annotation is used for traditional Spring controllers and has been part of the framework for a very long time.
  • The @RestController annotation was introduced in Spring 4.0 to simplify the creation of RESTful web services. It’s a convenience annotation that combines @Controller and @ResponseBody – which eliminates the need to annotate every request handling method of the controller class with the @ResponseBody annotation.
  • Classic controllers can be annotated with the @Controller annotation. This is simply a specialization of the @Component class and allows implementation classes to be autodetected through the classpath scanning.
  • The controller is annotated with the @RestController annotation, therefore the @ResponseBody isn’t required.

29. What is view resolver?

  • All MVC frameworks for web applications provide a way to address views. Spring provides view resolvers, which enable you to render models in a browser without tying you to a specific view technology.
  • * The two interfaces which are important to the way Spring handles views are ViewResolver and View. The ViewResolver provides a mapping between view names and actual views. The View interface addresses the preparation of the request and hands the request over to one of the view technologies.
  • Spring Boot JSP ViewResolver Configuration: To resolve JSP files location, you can have two approaches.

1) Add entries in application.properties

spring.mvc.view.prefix=/WEB-INF/view/
spring.mvc.view.suffix=.jsp

2) Configure InternalResourceViewResolver to serve JSP pages

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
 
@Configuration
@EnableWebMvc
@ComponentScan
public class MvcConfiguration extends WebMvcConfigurerAdapter
{
    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/view/");
        resolver.setSuffix(".jsp");
        resolver.setViewClass(JstlView.class);
        registry.viewResolver(resolver);
    }
}

30. How view data bind?

http://websystique.com/springmvc/spring-mvc-requestbody-responsebody-example/

  • @RequestBody and @ResponseBody annotations are used to bind the HTTP request/response body with a domain object in method parameter or return type. Behind the scenes, these annotation uses HTTP Message converters to convert the body of HTTP request/response to domain objects.

@RequestBody

  • * If a method parameter is annotated with @RequestBody, Spring will bind the incoming HTTP request body(for the URL mentioned in @RequestMapping for that method) to that parameter. While doing that, Spring will [behind the scenes] use HTTP Message converters to convert the HTTP request body into domain object [deserialize request body to domain object], based on Accept header present in request.
  • The Accept header is used by HTTP clients [browsers] to tell the server what content types they’ll accept.
  • The server sends back the response, which will include a Content-Type header telling the client what the content type of the returned content actually is. In case of POST or PUT request, browsers do send data in request, so they actually send content-type as well.
@RequestMapping(value="/user/create", method=RequestMethod.POST)
public ResponseEntity<Void> createUser(@RequestBody User user, UriComponentsBuilder ucBuilder){
    System.out.println("Creating User "+user.getName());
     
    if(userService.isUserExist(user)){
        System.out.println("A User with name "+user.getName()+" already exist");
        return new ResponseEntity<Void>(HttpStatus.CONFLICT);
    }
 
    userService.saveUser(user);
     
    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(user.getId()).toUri());
    return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}

@ResponseBody

  • If a method is annotated with @ResponseBody, Spring will bind the return value to outgoing HTTP response body. While doing that, Spring will [behind the scenes] use HTTP Message converters to convert the return value to HTTP response body [serialize the object to response body], based on Content-Type present in request HTTP header.
@RequestMapping(value = "/user/all", method = RequestMethod.GET)
public @ResponseBody List<User> listAllUsers() {
    return userService.findAllUsers();
}

31. @RequestParam vs @QueryParam vs @PathVariable vs @PathParam

FrameworkPath segmenthttp query parameter
Jersey (JAX-RS)@PathParam@QueryParam
Spring RESTFul@PathVariable@RequestParam
examplehttp://xyz.ir/{segment}http://xyz.ir/?param{param}
  • As shown in the table, the difference lies in where a value is read out. @PathParam reads the value from a path part of the called URI. @QueryParam is used to read the values ​​from QueryParameters of a URI call.
  • http://www.xyz.ir/ <@PathParam> /? queryParamName = <@QueryParm>

@PathVariable

@RequestMapping(value = "/orders/{id}", method = RequestMethod.GET)
@ResponseBody
public String getOrder(@PathVariable final String id) {
  return "Order ID: " + id;
}

32. What is RestTemplate?

https://www.tutorialspoint.com/spring_boot/spring_boot_rest_template.htm

  • Rest Template is used to create applications that consume RESTful Web Services. You can use the exchange() method to consume the web services for all HTTP methods.

33. What is RawMapper?

https://www.tutorialspoint.com/springjdbc/springjdbc_rowmapper.htm

  • The org.springframework.jdbc.core.RowMapper<T> interface is used by JdbcTemplate for mapping rows of a ResultSet on a per-row basis. Implementations of this interface perform the actual work of mapping each row to a result object.

37. Circular Dependencies in Spring

https://34codefactory.wordpress.com/2020/10/13/circular-dependencies-in-spring-code-factory/

38. Transaction Propagation and Isolation in Spring @Transactional

https://www.baeldung.com/spring-transactional-propagation-isolation

39. Difference between SOAP Vs. REST.

SOAPREST
SOAP stands for Simple Object Access ProtocolREST stands for Representational State Transfer
SOAP is a protocol. SOAP was designed with a specification. It includes a WSDL file which has the required information on what the web service does in addition to the location of the web service.REST is an Architectural style in which a web service can only be treated as a RESTful service if it follows the constraints of being
1. Client Server
2. Stateless
3. Cacheable
4. Layered System
5. Uniform Interface
SOAP cannot make use of REST since SOAP is a protocol and REST is an architectural pattern.REST can make use of SOAP as the underlying protocol for web services, because in the end it is just an architectural pattern.
SOAP uses service interfaces to expose its functionality to client applications. In SOAP, the WSDL file provides the client with the necessary information which can be used to understand what services the web service can offer.REST use Uniform Service locators to access to the components on the hardware device. For example, if there is an object which represents the data of an employee hosted on a URL as http://codefactory , the below are some of URI that can exist to access them

http://codefactory.com/Employee
http://codefactory.com/Employee/1
SOAP can only work with XML format. As seen from SOAP messages, all data passed is in XML format.REST permits different data format such as Plain text, HTML, XML, JSON, etc. But the most preferred format for transferring data is JSON.
  • SOAP requires more bandwidth for its usage. Since SOAP Messages contain a lot of information inside of it, the amount of data transfer using SOAP is generally a lot.
<?xml version="1.0"?>
<SOAP-ENV:Envelope 
xmlns:SOAP-ENV
="http://www.w3.org/2001/12/soap-envelope" 
SOAP-ENV:encodingStyle
=" http://www.w3.org/2001/12/soap-encoding">
   <soap:Body>
      <Demo.codefactoryWebService xmlns="http://tempuri.org/">
         <EmployeeID>int</EmployeeID>
      </Demo.codefactoryWebService>
   </soap:Body>
</SOAP-ENV:Envelope>
  • REST does not need much bandwidth when requests are sent to the server. REST messages mostly just consist of JSON messages. Below is an example of a JSON message passed to a web server. You can see that the size of the message is comparatively smaller to SOAP.
{"city":"Ahmedabad", "state":"Gujarat"}

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s