📜 ⬆️ ⬇️

Spring: job interview questions

image
This short list of questions will give you an understanding of the most important concepts of Spring, as well as help you prepare for an interview.


1 What is Component Scan for?

If you understand how Component Scan works, then you understand Spring


The first step to describe Spring Beans is to add annotations - @Component , or @Service , or @Repository .


However, Spring does not know anything about these bins, if he does not know where to look for them. What Spring will tell you where to look for these beans is called Component Scan. In @ComponentScan you specify the packets that should be scanned.


Spring will look for beans not only in scan packages, but also in their subpackages.


2 How do you add a Component Scan to Spring Boot?
 @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } 

@SpringBootApplication defines automatic scanning of the package where the Application class is located


Everything will be fine, your code is entirely in the specified package or its subpackages.


However, if the component you need is in a different package, you must additionally use the @ComponentScan annotation, where you can list all additional packages for scanning.


3 What is the difference between @Component and @ComponentScan?

@Component and @ComponentScan are intended for different purposes.


@Component marks the class as a candidate for creating the Spring bean.
@ComponentScan indicates where Spring @ComponentScan for classes marked with the annotation @Component or its derivative


4 What is the @Bean annotation used for?

In Spring configuration classes, @Bean used to define components with custom logic.


5 What is the difference between @Bean and @Component?

@Bean used in Spring configuration classes. It is used to directly create a bean.


@Component used with all classes that Spring should manage. When Spring sees a class with @Component , Spring identifies this class as a candidate for creating a bean.


6 What is the difference between @Component, @Service and @Repository annotations?

They all define Spring beans. However, there is a difference between them.


@Component is a universal component
@Repository is a component that is intended for storage, retrieval and retrieval. Typically used to work with databases.
@Service - a facade for some business logic


Custom annotations derived from @Component can add special logic in bins.


For example, bins @Repository using @Repository additionally have processing for JDBC Exception.


7 Can we use @Component instead of @Service for business logic?

Yes. of course.


If @Component is a universal stereotype for any Spring component, then @Service is currently its alias. However, in the official Spring documentation, it is recommended to use @Service for business logic. It is quite possible that in future versions of the framework, additional semantics will be added for this stereotype, and its bins will have additional logic.


8 What is the difference between web.xml and the Spring Context - servlet.xml?

web.xml — The metadata and configuration of any Java EE compliant web application. Java EE standard for web applications.
servlet.xml is the Spring Framework-specific configuration file.


9 What do you prefer to use for Spring configuration - xml or annotation?

I prefer annotations if the codebase is well described by elements such as @Service, @Component, @Autowired


However, when it comes to configuration, I do not have any preferences. I would leave this question to the team.


10 Can we apply @Autowired with non-setters and non-constructor methods?

Yes of course.


@Autowired can be used with constructors, setters, or any other methods. When Spring finds @Autowired on a method, Spring will automatically call this method, after creating a bean instance. As arguments, matching objects from the Spring context will be selected.


11 What is the difference between Cross Cutting Concerns and AOP (aspect-oriented programming)?

End-to-End Functionality — functionality that you may need at several different levels — logging, performance management, security, etc.
AOP is one of the approaches to the implementation of this problem.


12 What is the difference between IOC (Inversion of Control) and Application Context?

IOC - inversion of control. Instead of manually introducing dependencies, the framework takes responsibility for this.
ApplicationContext - implementation of IOC spring.


Bean Factory is the basic version of the IOC container


The application context also includes additional features that are typically needed for developing enterprise applications.


13 What is the difference between classPathXmlApplicationContext and annotationConfigApplicationContext?

classPathXmlApplicationContext - if you want to initialize the Spring context using xml
annotationConfigApplicationContext - if you want to initialize the Spring context using the java configuration class


14 Why can the return value be lost when using the @Around aspect? What are the reasons?

The method marked with the @Around annotation should return the value it (method) obtained from joinpoint.proceed ()


 @Around("trackTimeAnnotation()") public Object around(ProceedingJoinPoint joinPoint) throws Throwable{ long startTime = System.currentTimeMillis(); Object retVal = joinPoint.proceed(); long timeTaken = System.currentTimeMillis() - startTime; logger.info("Time taken by {} is equal to {}",joinPoint, timeTaken); return retVal; } 

15 How do you decide which bean to inject if you have several suitable beans. Tell us about @Primary and @Qualifier?

If there is a bin that you prefer most of the time compared to others, then use @Primary , and use @Qualifier for non-standard scripts.


If all bins have the same priority, we will always use @Qualifier


If the bin must be selected during the execution of the program, these annotations will not work for you. You need to create a method in the configuration class, mark it with the @Bean annotation, and return the required bin to them.


16 What's New in the Spring Framework 5.0?

In my opinion, this is the Functional Web Framework, Kotlin, and support for reactive programming.


17 Compare the Application Context, IOC Container, vs Web Container and EJB Container. Do I need a Web Container to run Spring Boot applications?

Web Container and EJB Containers are part of an application / web server, such as Tomcat, Websphere, Weblogic. They add their extra functionality to them. Java EE defines a contract for web applications, these containers are the implementation of these contracts.


Spring container can be part of any application that you do in java. Spring can work inside the web container, ejb container or even without them.


18 How can we select the appropriate bin using application.properties?

Consider an example:


 interface GreetingService { public String sayHello(); } 

And two components


 @Component(value="real") class RealGreetingService implements GreetingService { public String sayHello() { return "I'm real"; } } @Component(value="mock") class MockGreetingService implements GreetingService { public String sayHello() { return "I'm mock"; } } 

Then add the property to application.properties
application.greeting: real


We use this solution:


 @RestController public class WelcomeController { @Resource(name="${application.greeting}") private GreeterService service1; } 

19 What is the minimum Java version supported in Spring Boot 2 and Spring 5?

Spring 5.0 and Spring Boot 2.0 support Java 8 and later.


20 What is the difference between @Controller and @RestController?

@RestController = @Controller + @ResponseBody


@RestController turns the tagged class into a Spring bean. This bean uses the Jackson message converter to convert incoming / outgoing data. As a rule, target data is presented in json or xml.


21 Why do we sometimes use @ResponseBody and sometimes ResponseEntity?

ResponseEntity is needed only if we want to customize the response by adding the response status to it. In all other cases we will use @ResponseBody.


 @GetMapping(value=”/resource”) @ResponseBody public Resource sayHello() { return resource; } @PostMapping(value=”/resource”) public ResponseEntity createResource() { …. return ResponseEntity.created(resource).build(); } 

Standard HTTP response status codes that can be used.
200 - SUCCESS
201 - CREATED
404 - RESOURCE NOT FOUND
400 - BAD REQUEST
401 - UNAUTHORIZED
500 - SERVER ERROR


For @ResponseBody, the only status states are SUCCESS (200), if everything is OK and SERVER ERROR (500), if any error has occurred.


Suppose we have created something and want to send the status CREATED (201). In this case, we use ResponseEntity.


22 What is the difference between Filters, Listeners and Interceptors?

Conceptually, everything is simple, servlet filters can intercept only HTTPServlets. Listeners can capture specific events. How to intercept events that relate to none other?


Filters and interceptors do essentially the same thing: they intercept an event, and do something before or after.


Java EE uses the term Filter, Spring calls them Interceptors.


It is here that AOP is used in full force, so that it is possible to intercept calls of any objects


23 What is the difference between ModelMap and ModelAndView?

Model - interface, ModelMap its implementation ..


ModelAndView is a container for a pair, like ModelMap and View.


I usually like to use ModelAndView. However, there is also a way when we set the necessary attributes in the ModelMap, and return the name View with the usual string from the controller method.


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

The addAttribute method separates us from working with the basic hashmap structure. In essence, addAttribute is a wrapper over put, where an additional check for null is done. The addAttribute method, unlike put, returns a modelmap.
model.addAttribute (“attribute1”, ”value1”). addAttribute (“attribute2”, ”value2”);


25 What can you say about Form Binding?

We may need this if, for example, we want to take some value from the HTML page and save it to the database. For this we need to move this value to the Spring controller.


If we use Spring MVC form tags, Spring will automatically associate variables on the HTML page with Bin Spring.


If I have to work with this, I will definitely watch the official Spring MVC Form Tags documentation.


26 Why do we use the Hibernate Validator?

Hibernate Validator has nothing to do with the database. This is just a validation library.


Hibernate Validator version 5.x is a reference implementation of Bean Validation 1.1


Also, if you take a look at http://beanvalidation.org/2.0 , then the Hibernate Validator is the only one that is certified.


27 Where should static (css, js, html) resources be located in a Spring MVC application?

The location of static resources can be customized. The Spring Boot documentation recommends using / static, or / public, or / resources, or / META-INF / resources


28 Why is it recommended to use POST for confidential data and not GET requests?

In the case of a GET request, the parameters passed are part of the url, and all the routers through which our GET request passes will be able to read them.


In the case of a POST request, the parameters passed are part of the request body. When using HTTPs, the request body is encrypted. Therefore, using POST requests is safer.


29 Is it possible to pass the same parameter in the request several times?

Example:
http://localhost:8080/login?name=Ranga&name=Ravi&name=Sathish
Yes, you can accept all values ​​using an array in the controller method


 public String method(@RequestParam(value="name") String[] names){ } 

I want to thank the user Habr jd2050 , for helping with the translation.


')

Source: https://habr.com/ru/post/350682/


All Articles