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.
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.
@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.
@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
In Spring configuration classes, @Bean
used to define components with custom logic.
@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.
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.
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.
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.
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.
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.
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.
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.
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
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; }
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.
In my opinion, this is the Functional Web Framework, Kotlin, and support for reactive programming.
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.
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; }
Spring 5.0 and Spring Boot 2.0 support Java 8 and later.
@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.
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.
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
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.
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”);
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.
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.
The location of static resources can be customized. The Spring Boot documentation recommends using / static, or / public, or / resources, or / META-INF / resources
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.
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