Showing posts with label dependency injection. Show all posts
Showing posts with label dependency injection. Show all posts

Tuesday, August 18, 2020

Interview questions on spring

 Hi friends,

In this post, I am sharing interview questions and answers based on spring concepts.


Question 1:

List all the spring core , stereotype annotations, spring boot annotations and spring MVC and WEB annotations.

Answer:

  • @Qualifier
  • @Autowired
  • @Required
  • @ComponentScan
  • @Configuration
  • @Bean
  • @Lazy
  • @Value

Spring Framework Stereotype annotations:

  • @Component
  • @Controller
  • @Service
  • @Repository

Spring Boot Annotations:

 

  • @EnableAutoConfiguration
  • @SpringBootApplication

 

Spring MVC and REST[WEB]  Annotations:

 

  • @Controller
  • @RequestMapping
  • @CookieValue
  • @CrossOrigin
  • @GetMapping
  • @PostMapping
  • @PutMapping
  • @DeleteMapping
  • @PatchMapping
  • @ExceptionHandler
  • @InitBinder
  • @Mappings and @Mapping
  • @MatrixVariable
  • @PathVariable
  • @RequestAttribute
  • @RequestBody
  • @RequestHeader
  • @RequestParam
  • @RequestPart
  • @ResponseBody
  • @ResponseStatus
  • @ControllerAdvice
  • @RestController
  • @RestControllerAdvice
  • @SessionAttribute
  • @SessionAttributes


Question 2:

What is the use of @Required annotation?

Answer:

It is required when we want to ensure that all the required properties have been set.

In Spring, there is dependency-check attribute and using this we can only check whether the properties has been set or not. But we can’t check if their value is set to null or non-null.

Using @Required annotation we can check if values are set to non-null.

It is used on setter methods.

While using @Required, we should register RequiredAnnotationBeanPostProcessor class that checks if all the bean properties with the @Required annotation has been set.

applicationContext.xml ->

<bean id="manager"  class="com.howtodoinjava.demo.factory.EmployeeFactoryBean">

    <!-- <property name="designation" value="Manager" /> -->

</bean>

 

<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor" />

 

 

Note: If any property with @Required annotation have not been set, a BeanInitializationException will be thrown by this bean post processor.

In this way, you can use @Required annotation and RequiredAnnotationBeanPostProcessor class to verify that on context initialization, all the required bean properties have been set properly.


Question 3:

What is the use of @Value annotation?

Answer:

This annotation is used to assign default value to variables and method arguments. We can read Spring environment variables and System variables as well.

@Value only takes String values.


@Value("true")

private boolean defaultBoolean;

@Value("10")

private int defaultInt; 


@Value("Test")

public void printValues(String s, String v) // Both s and v values will be test.


@Value("Test")

public void printValues(String s, @Value("Data") String v) // Here s will be Test and v will be Data.



Question 4:

What are available spring framework modules?

Answer:

  • Spring Core module
  • Spring MVC module
  • Spring Context [J2EE]
  • Spring DAO module
  • Spring ORM module
  • Spring AOP


Question 5:

What are the different features of spring framework?

Answer:

There are multiple features in spring framework.


  • Lightweight: Spring is lightweight when it comes to size and transparency. 
  • Inversion of control (IOC): The objects give their dependencies instead of creating or looking for dependent objects. This is called Inversion Of Control.
  • Aspect oriented Programming (AOP): Aspect oriented programming in Spring supports cohesive development by separating application business logic from system services.
  • Container: Spring Framework creates and manages the life cycle and configuration of the application objects.
  • MVC Framework: Spring Framework’s MVC web application framework is highly configurable. Other frameworks can also be used easily instead of Spring MVC Framework.
  • Transaction Management: Generic abstraction layer for transaction management is provided by the Spring Framework. Spring’s transaction support can be also used in container less environments.
  • JDBC Exception Handling: The JDBC abstraction layer of the Spring offers an exception hierarchy, which simplifies the error handling strategy.

 


Question 6:

What are the different components of a spring application?

Answer:

A Spring application, generally consists of following components:

  • Interface: It defines the functions.
  • Bean class: It contains properties, its setter and getter methods, functions etc.
  • Spring Aspect Oriented Programming (AOP): Provides the functionality of cross-cutting concerns.
  • Bean Configuration File: Contains the information of classes and how to configure them.
  • User program: It uses the function.

 

Question 7:

What do we mean by dependency injection?

Answer:

In Dependency Injection, we do not have to create your objects but have to describe how they should be created. 

We don’t connect your components and services together in the code directly, but describe which services are needed by which components in the configuration file. The IoC container will wire them up together.


Question 8:

What are the benefits of using IOC in spring?

Answer:

Some of the benefits of IOC are:

  • It will minimize the amount of code in your application.
  • It will make your application easy to test because it doesn’t require any singletons or JNDI lookup mechanisms in your unit test cases.
  • It promotes loose coupling with minimal effort and least intrusive mechanism.
  • It supports eager instantiation and lazy loading of the services.

 


That's all for this post.

Thanks for reading!!

Tuesday, August 4, 2020

Java Technical Interview @ CandelaLabs

Hi Friends,

In this post, I'm sharing interview questions answers asked in telephonic round of CandelaLabs.

You can also read my other interviews:



Question1: 

What is DispatcherServlet and why it is used for?

Answer:

The DispatcherServlet is the implementation of front controller design pattern that handles all incoming web requests to a spring MVC application.
A front controller pattern is a common pattern in web applications whose job is to receive all requests and route it to different components of application for actual processing.

In Spring MVC, the DispatcherServlet routes web requests to spring MVC controllers.

DispatcherServlet uses handler mapping like @RequestMapping annotation to find correct controller to process a request.

It s also responsible for delegating logical view name to ViewResolver and then sending the rendered response to the client.



Question 2:

What is the root application context in spring MVC? How is it loaded?

Answer:

In Spring MVC, the context loaded using ContextLoaderListener  is called the root application context which belongs to the whole application. While the one initialized using DispatcherServlet is actually specific to that servlet.

Technically, spring MVC allows multiple DispatcherServlet in a spring MVC web application and so are multiple contexts , each specific for the specific servlet. 



Question 3:

How many types of Dependency injection types are there in Spring?
 
Answer:

Spring documentation strictly defines only twp types of injection : constructor and setter injection.

However there are more ways to inject a dependency like a field injection , lookup method injection.

Constructor Injection: Enforcing immutability:

In this, a dependent class has a constructor , where all dependencies are set. These will be provided by spring container according to xml, java or annotation based configuration.

 e.g.:

class Service1{

}

class Service2{

}

class DependentService{
    private Service1 ser1;
    private Service2 ser2;

    public DependentService(Service ser1, Service2 ser2){
        this.ser1 = ser1;
        this.ser2 = ser2;
    }
}


public class Main{

    public static void main(String[] args){

        ApplicationContext container = new ClassPathApplicationContext("spring.xml");

        (DependentService) container.getBean("dependentService");
    }
}


spring.xml is:

<?xml version = "1.0" encoding = "utf-8"?>
    // bean xmlns namespaces goes here.....

    <bean id = "service1" classs ="eample.service1"/>
    <bean id = "service2" class = "example.service2"/>

    <bean id="deoenddentService" class = "example.DepenentService">
        <constructor-arg type = "example.Service1" ref = "service1"/>
        <constructor-arg type = "example.Service2" ref = "service2"/>
    </bean>



Constructor injection using annotation:

@Service
class Service1{

}

@Service
class Service2{

}

@Service
class DependentService{

    private final Service1 ser1;
    private final Service2 ser2;

    @Autowired
    public DependentService(Service1 ser1, Service2 ser2){
        
        this.ser1 = ser1;
        this.ser2 = ser2;
    }

}

public class Main{

    public static void main(String[] args){

        ApplicationContext container = new ClassPathAppplicationContext("spring.xml");
        (DependentService) container.getBean("dependentService");
    
    }
}

Now in spring.xml file:

we do not need to add any <bean>.

Just add <context:component-scan base-package= "example"/>

Drawback of this approach: 

We need to use @Qualifier annotation to tell spring, which implementation of a specific interface to use , in case w e are using two implementations of an interface.

Higher chance to have circular dependencies.


Note: We can have many more constructors in or class, but only one of them should qualify for dependency injection.


Advantage of this approach: Can be combined with setter injection and field injection.


Setter injection:

With XML:

class Service1{

}


class Service2{

}

class DependentService{

    private Service1 ser1;
    private Service2 ser2;

    public DependentService(){

        
    }

    public void setService1(Service1 ser1){

        this.ser1 = ser1;
    }

    public void setService2(Service2 ser2){
    
        this.ser2 = ser2;
    }

}

XML is:

<bean id = "service1" class = "example.Service1"/>
<bean id= "service2" class = "example.Service2"/>

<bean id = "dependentService" class = "example.DependentService">
    <property name="service1" ref="service1"/>
    <property name="service2" ref="service2"/>
</bean>


Setter Injection with annotations:

class Service1{

}


class Service2{

}

class DependentService{

    private Service1 ser1;
    private Service2 ser2;

    public DependentService(){

        
    }

    @Autowired
    public void serService1(Service1 ser1){

        this.ser1 = ser1;
    }

     @Autowired
     public void setService2(Service2 ser2){
    
        this.ser2 = ser2;
    }

}


Note: We can combine setter injection and constructor injection.

  
Field Injection:

@Service
class DependentService{

    @Autowired
    private Service1 ser1;
    
    @Autowired
    private Service2 ser2;
}


Advantages:

  • Easy to use. No constructors or setters required.
  • Can be easily combined with the constructor and /or setter approach.

Disadvantages:

  • A number of dependencies can reach dozens until we notice that something went wrong in the design.



Question 4:

What are java Microservices frameworks?

Answer:

There are multiple java microservices frameworks:

  • Spring and Spring boot
  • DropWizard
  • Eclipse MicroProfile

Spring and Spring Boot:

    The framework propagates building the application into a jar and running it on the embedded Tomcat server , making it a perfect combination with Docker to manage a virtualized  deployment environment.

DropWizard:

Like Spring boot, DropWizard application is packages into jar file with the jetty server embedded.

DropWizard integrates the tried-and-tested java libraries into a fully functional platform: Jersey for REST, Jackson for JSON, Freemarker for template   and Mustache for java based UIs.

DropWizard ships with no built-in dependency injection solution, but integrations exist for Guice and Dagger.




Thanks for reading!!.
 

CAP Theorem and external configuration in microservices

 Hi friends, In this post, I will explain about CAP Theorem and setting external configurations in microservices. Question 1: What is CAP Th...