In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/03 Report--
Spring Framework is now almost the standard framework for Java Web development. So, as a Java programmer, how much do you know about the main technical points of Spring? You might as well use the questions in this article to test it.
1. General questions
1.1. What are the main functions of different versions of Spring Framework?
Version Feature
Spring 2.5 was released in 2007. This is the first version that supports annotations.
Spring 3.0 was released in 2009. It takes full advantage of the improvements in Java5 and provides support for JEE6.
Spring 4.0 was released in 2013. This is the first version that fully supports JAVA8.
1.2. What is Spring Framework?
Spring is an open source application framework designed to reduce the complexity of application development.
It is lightweight and loosely coupled.
It has a hierarchical architecture that allows users to select components and provides a cohesive framework for J2EE application development.
It can integrate other frameworks, such as Structs, Hibernate, EJB, etc., so it is also called the framework of the framework.
1.3. List the advantages of Spring Framework.
Because of the hierarchical architecture of Spring Frameworks, users are free to choose the components they need.
Spring Framework supports POJO (Plain Old Java Object) programming for continuous integration and testability.
JDBC is simplified due to dependency injection and control reversal.
It is open source and free.
1.4. What are the different functions of Spring Framework?
Lightweight-Spring is lightweight in terms of code volume and transparency.
IOC-Control inversion
AOP-aspect-oriented programming separates application business logic from system services to achieve high cohesion.
Container-Spring is responsible for creating and managing the lifecycle and configuration of objects (Bean).
MVC-provides a high degree of configurability for web applications and easy integration with other frameworks.
Transaction management-provides a common layer of abstraction for transaction management. Spring's transaction support can also be used in environments with fewer containers.
JDBC exceptions-Spring's JDBC abstraction layer provides an exception hierarchy that simplifies error handling strategies.
1.5. How many modules are there in Spring Framework and what are they?
Spring Core Container-this layer is basically the core of Spring Framework. It contains the following modules:
Spring Core
Spring Bean
SpEL (Spring Expression Language)
Spring Context
Data access / Integration-this layer provides support for interacting with the database. It contains the following modules:
JDBC (Java DataBase Connectivity)
ORM (Object Relational Mapping)
OXM (Object XML Mappers)
JMS (Java Messaging Service)
Transaction
Web-this layer provides support for creating Web applications. It contains the following modules:
Web
Web-Servlet
Web-Socket
Web-Portlet
AOP-this layer supports aspect-oriented programming
Instrumentation-this layer provides support for class detection and class loader implementation.
Test-this layer provides support for testing with JUnit and TestNG.
Several miscellaneous modules:
Messaging-this module provides support for STOMP. It also supports the annotated programming model, which is used to route and process STOMP messages from WebSocket clients.
Aspects-this module provides support for integration with AspectJ.
1.6. What is a Spring profile?
The Spring configuration file is a XML file. This file mainly contains class information. It describes how these classes are configured and introduced into each other. However, the XML configuration file is lengthy and cleaner. If it is not planned and written correctly, it becomes very difficult to manage in large projects.
1.7. What are the different components of a Spring application?
Spring applications generally have the following components:
Interface-defines the function.
Bean class-it contains properties, setter and getter methods, functions, and so on.
Spring facet oriented programming (AOP)-provides facet oriented programming capabilities.
Bean configuration file-contains information about classes and how to configure them.
User program-it uses interfaces.
1.8. What are the ways to use Spring?
You can use Spring in the following ways:
As a mature Spring Web application.
As a third-party Web framework, the Spring Frameworks middle tier is used.
For remote use.
As an enterprise Java Bean, it can wrap existing POJO (Plain Old Java Objects).
2. Dependency injection (Ioc)
2.1. What is a Spring IOC container?
The core of the Spring framework is the Spring container. The container creates objects, assembles them, configures them, and manages their full lifecycle. The Spring container uses dependency injection to manage the components that make up the application. The container receives instructions for instantiation, configuration, and assembly of objects by reading the configuration metadata provided. This metadata can be provided through XML,Java annotations or Java code.
2.2. What is dependency injection?
In dependency injection, you do not have to create objects, but you must describe how to create them. Instead of connecting components and services directly in your code, you describe which components in the configuration file require which services. They are assembled together by an IoC container.
2.3. How many ways can dependency injection be done?
Typically, dependency injection can be done in three ways, namely:
Constructor injection
Setter injection
Interface injection
In Spring Framework, only constructors and setter injection are used.
2.4. Distinguish between constructor injection and setter injection.
Constructor injection setter injection
There is no partial injection.
The setter property is not overridden, the setter property is overridden
Any modification will create a new instance. Any modification will not create a new instance.
Suitable for setting many properties for setting a small number of properties
2.5. How many IOC containers are there in spring?
BeanFactory-BeanFactory is like a factory class that contains a collection of bean. It instantiates the bean when required by the client.
The ApplicationContext-ApplicationContext interface extends the BeanFactory interface. It provides some additional functions on top of BeanFactory.
2.6. Distinguish between BeanFactory and ApplicationContext.
BeanFactory ApplicationContext
It uses lazy loading. It uses instant loading.
It uses syntax to explicitly provide resource objects. It creates and manages resource objects itself.
Internationalization is not supported.
Dependency based annotations are not supported. Dependency based annotations are supported.
2.7. List some of the benefits of IoC.
Some of the benefits of IoC are:
It minimizes the amount of code in the application.
It will make your application easy to test because it does not require any singleton or JNDI lookup mechanism in the unit test case.
It promotes loose coupling with the least impact and the least intrusion mechanism.
It supports instant instantiation and delayed loading services.
2.8. The implementation mechanism of Spring IoC.
The implementation principle of IoC in Spring is factory mode plus reflection mechanism.
Example:
Interface Fruit {
Public abstract void eat ()
}
Class Apple implements Fruit {
Public void eat () {
System.out.println ("Apple")
}
}
Class Orange implements Fruit {
Public void eat () {
System.out.println ("Orange")
}
}
Class Factory {
Public static Fruit getInstance (String ClassName) {
Fruit f=null
Try {
F = (Fruit) Class.forName (ClassName). NewInstance ()
} catch (Exception e) {
E.printStackTrace ()
}
Return f
}
}
Class Client {
Public static void main (String [] a) {
Fruit f=Factory.getInstance ("io.github.dunwu.spring.Apple")
If (favored null) {
F.eat ()
}
}
}
Beans
3.1. What is spring bean?
They are the objects that make up the backbone of the user's application.
Bean is managed by the Spring IoC container.
They are instantiated, configured, assembled, and managed by the Spring IoC container.
The Bean is created based on the configuration metadata provided by the user to the container.
3.2. What configuration methods does spring provide?
Xml-based configuration
The dependencies and services required by bean are specified in the configuration file in XML format. These configuration files typically contain many bean definitions and application-specific configuration options. They usually start with a bean tag. For example:
Annotation-based configuration
Instead of using XML to describe bean assemblies, you can configure bean as the component class itself by using annotations on related class, method, or field declarations. Annotation assemblies are not open by default in the Spring container. Therefore, you need to enable it in the Spring configuration file before using it. For example:
Java API-based configuration
Spring's Java configuration is achieved by using @ Bean and @ Configuration.
The @ Bean annotation plays the same role as the element.
The @ Configuration class allows you to define dependencies between bean by simply calling other @ Bean methods in the same class.
For example:
@ Configuration
Public class StudentConfig {@ Beanbr/ > @ Bean
Return new StudentBean ()
}
}
3.3. Spring supports centralized bean scope?
Spring bean supports five types of scope:
Singleton-there is only one single instance per Spring IoC container.
Prototype-A new instance is generated for each request.
Request-each HTTP request generates a new instance, and the bean is valid only within the current HTTP request.
Session-each HTTP request generates a new bean, and the bean is only valid within the current HTTP session.
Global-session-similar to the standard HTTP Session scope, but it only makes sense in portlet-based web applications. The Portlet specification defines the concept of global Session, which is shared by all the different portlet that make up a portlet web application. The bean defined in the global session scope is limited to the lifecycle of the global portlet Session. If you use the global session scope in web to identify bean, then web is automatically used as a session type.
The last three are available only if the user is using ApplicationContext that supports Web.
3.4. What is the life cycle of a spring bean container?
The lifecycle process of the spring bean container is as follows:
The 1Spring container instantiates the bean according to the bean definition in the configuration.
2Spring populates all properties with dependency injection, such as the configuration defined in bean.
3 if bean implements the BeanNameAware interface, the factory calls setBeanName () by passing the ID of the bean.
4 if bean implements the BeanFactoryAware interface, the factory calls setBeanFactory () by passing its own instance.
5 if there is any BeanPostProcessors associated with bean, the preProcessBeforeInitialization () method is called.
6 if the init method (the init-method property of) is specified for bean, it will be called.
7 finally, if there is any BeanPostProcessors associated with bean, the postProcessAfterInitialization () method is called.
8 if bean implements the DisposableBean interface, destory () is called when the spring container is closed.
9 if the destroy method (the destroy-method property of) is specified for bean, it will be called.
3.5. What is the internal bean of spring?
A bean can be declared as an internal bean only if it is used as an attribute of another bean. XML-based configuration metadata for defining bean,Spring provides the use of elements in or. Internal bean is always anonymous, and they are always used as prototypes.
For example, suppose we have a Student class that references the Person class. Here we will only create an instance of the Person class and use it in Student.
Student.java
Public class Student {
Private Person person
/ / Setters and Getters
}
Public class Person {
Private String name
Private String address
/ / Setters and Getters
}
Bean.xml
3.6. What is spring Assembly
When bean is grouped together in a Spring container, it is called assembly or bean assembly. The Spring container needs to know what bean is needed and how the container should use dependency injection to bind the bean together while assembling the bean.
3.7. What are the ways of automatic assembly?
Spring containers can automatically assemble bean. That is, you can have Spring automatically parse bean's collaborators by checking the contents of BeanFactory.
Different modes of automatic assembly:
No-this is the default setting, indicating that there is no automatic assembly. Explicit bean references should be used for assembly.
ByName-it injects object dependencies based on the name of the bean. It matches and assembles the bean whose properties are defined by the same name in the XML file.
ByType-it injects object dependencies based on type. If the type of the attribute matches a bean name in the XML file, the attribute is matched and assembled.
Constructor-it injects dependencies by calling the constructor of the class. It has a lot of parameters.
Autodetect-first the container tries to assemble using autowire through the constructor, and if not, it tries to assemble automatically through byType.
3.8. What are the limitations of automatic assembly?
Override possibility-you can always use and set specified dependencies, which will override autoassembly.
Basic metadata types-simple properties (such as original data types, strings, and classes) cannot be automatically assembled.
Confusing nature-always likes to use explicit assembly because automatic assembly is not very accurate.
4. Notes
4.1. What is annotation-based container configuration
Instead of using XML to describe bean assemblies, developers move the configuration to the component class itself by using annotations on related class, method, or field declarations. It can be used as an alternative to XML settings. For example:
Spring's Java configuration is achieved by using @ Bean and @ Configuration.
@ Bean annotations play vs.
The same role as the element.
The @ Configuration class allows you to define dependencies between bean by simply calling other @ Bean methods in the same class.
For example:
@ Configuration
Public class StudentConfig {@ Beanbr/ > @ Bean
Return new StudentBean ()
}
}
4.2. How do I start annotation assembly in spring?
Annotation assemblies are not open by default in the Spring container. Therefore, to use annotation-based assembly, we must enable it in the Spring configuration file through the configuration element.
4.3. What's the difference between @ Component, @ Controller, @ Repository, @ Service?
Component: this marks the java class as bean. It is a common stereotype for any Spring management component. Spring's component scanning mechanism can now pick it up and pull it into the application environment.
Controller: this marks a class as a Spring Web MVC controller. The Bean marked with it is automatically imported into the IoC container.
Service: this annotation is a specialization of component annotations. It does not provide any other behavior for the @ Component annotation. You can use @ Service instead of @ Component in the service layer class because it specifies the intent in a better way.
Repository: this annotation is a specialization of @ Component annotations with similar uses and functions. It provides additional benefits for DAO. It imports DAO into the IoC container and qualifies unchecked exceptions to be converted to Spring DataAccessException.
4.4. What is the use of @ Required annotations?
@ Required is applied to the bean property setter method. This annotation only indicates that the affected bean property must be populated with explicit property values in the bean definition or auto-assembly at configuration time. If the affected bean property has not been populated, the container throws a BeanInitializationException.
Example:
Public class Employee {
Private String name;@Requiredbr/ > @ Required
This.name=name
}
Public string getName () {
Return name
}
}
4.5. What is the use of @ Autowired annotations?
@ Autowired gives you more precise control over where and how to automate assembly. This annotation is used to automatically assemble bean on setter methods, constructors, properties or methods with arbitrary names or parameters. By default, it is type-driven injection.
Public class Employee {
Private String name;@Autowiredbr/ > @ Autowired
This.name=name
}
Public string getName () {
Return name
}
}
4.6. What is the use of @ Qualifier annotations?
When you create multiple bean of the same type and want to assemble only one of the bean with attributes, you can use the @ Qualifier annotation and @ Autowired to disambiguate by specifying which exact bean should be assembled.
For example, here we have two classes, Employee and EmpAccount. In EmpAccount, use @ Qualifier to specify that you must assemble a bean with an id of emp1.
Employee.java
Public class Employee {
Private String name;@Autowiredbr/ > @ Autowired
This.name=name
}
Public string getName () {
Return name
}
}
EmpAccount.java
Public class EmpAccount {
Private Employee emp
@ Autowired@Qualifier (emp1) br/ > @ Qualifier (emp1)
System.out.println ("Employee name:" + emp.getName)
}
}
4.7. What is the use of @ RequestMapping annotations?
The @ RequestMapping annotation is used to map a specific HTTP request method to a specific class / method in the controller that will process the corresponding request. This comment can be applied to two levels:
Class level: map the requested URL
Method level: mapping URL and HTTP request methods
5. Data access
5.1. What's the use of spring DAO?
Spring DAO makes it easier for data access technologies such as JDBC,Hibernate or JDO to work in a unified way. This makes it easy for users to switch between persistence technologies. It also allows you to write code without having to worry about catching different exceptions for each technology.
5.2. Enumerate the exceptions thrown by Spring DAO.
5.3. What classes exist in spring JDBC API?
JdbcTemplate
SimpleJdbcTemplate
NamedParameterJdbcTemplate
SimpleJdbcInsert
SimpleJdbcCall
5.4. What are the ways to access Hibernate using Spring?
We can use Spring to access Hibernate in two ways:
Control inversion using Hibernate templates and callbacks
Extend HibernateDAOSupport and apply AOP interceptor node
5.5. List the transaction management types supported by spring
Spring supports two types of transaction management:
Programmatic transaction management: in this process, manage transactions with the help of programming. It gives you great flexibility, but it is very difficult to maintain.
Declarative transaction management: here, transaction management is separated from the business code. Only annotations or XML-based configurations are used to manage transactions.
5.6. Which ORM frameworks are supported by spring
Hibernate
IBatis
JPA
JDO
OJB
6 、 AOP
6.1. What is AOP?
AOP (Aspect-Oriented Programming), that is, aspect-oriented programming, complements OOP (Object-Oriented Programming, object-oriented programming) and provides a perspective of abstract software structure different from OOP.
In OOP, we use class as our basic unit, while the basic unit in AOP is Aspect (aspect).
6.2. What is Aspect?
Aspect consists of pointcount and advice, which contains not only the definition of crosscutting logic, but also the definition of join point. Spring AOP is the framework responsible for implementing the section, which weaves the crosscutting logic defined by the section into the connection point specified by the section.
The focus of AOP's work is on how to enhance the join point of the weaving target object, which includes two tasks:
1 how to locate to a specific joinpoint through pointcut and advice
How to write section code in advice.
You can simply think of a class annotated with @ Aspect as an aspect.
6.3. What is a JoinPoint
Some point in time when a program is running, such as the execution of a method, or the handling of an exception.
In Spring AOP, join point is always the point of execution of a method.
6.4. What is an Advice?
The action taken by the Aspect at a particular JoinPoint is called Advice. Spring AOP uses an Advice as an interceptor to maintain a series of interceptors "around" the JoinPoint.
6.5. What types of notifications are there (Advice)?
Before-these types of Advice are executed before the joinpoint method and are configured using the @ Before annotation tag.
AfterReturning-these types of Advice are executed after the join point method is executed normally and are configured with the @ AfterReturning annotation tag.
AfterThrowing-these types of Advice are executed only when the joinpoint method exits by throwing an exception and is configured with @ AfterThrowing annotations.
After (finally)-these types of Advice are executed after the join point method, regardless of whether the method exit is normal or abnormal, and are configured with the @ After annotation tag.
Around-these types of Advice are executed before and after the join point and are configured using the @ Around annotation tag.
6.6. The differences between concern and cross-cutting concern in spring aop are pointed out.
Concern is the behavior that we want to define in a specific module of the application. It can be defined as the function we want to implement.
Cross-cutting concern is a behavior that applies to the entire application, which affects the entire application. For example, logging, security, and data transfer are issues that almost every module of an application needs to pay attention to, so they are cross-domain issues.
6.7. What are the ways to implement AOP?
The technologies for implementing AOP are mainly divided into two categories:
Static proxy-refers to compilation using commands provided by the AOP framework so that AOP proxy classes can be generated at compile time, so it is also known as compile-time enhancement
Compile-time weaving (special compiler implementation)
Weaving when class loading (special class loader implementation).
Dynamic proxy-AOP dynamic proxy classes are generated "temporarily" in memory at run time, so they are also called runtime enhancements.
JDK dynamic agent
CGLIB
6.8. What's the difference between Spring AOP and AspectJ AOP?
Spring AOP is implemented based on dynamic proxy, while AspectJ is implemented based on static proxy.
Spring AOP supports only method-level PointCut;. It provides full AOP support, and it also supports attribute-level PointCut.
6.9. How to understand agents in Spring?
The object created after applying the Advice to the target object is called a proxy. In the case of a client object, the target object and the proxy object are the same.
Advice + Target Object = Proxy
6.10. What is Weaving?
Linking an aspect and other application types or objects in order to create an advice object is called Weaving. In Spring AOP, weaving is performed at run time. Please refer to the following figure:
7 、 MVC
7.1. What is the use of the Spring MVC framework?
The Spring Web MVC framework provides a model-view-controller architecture and ready-to-use components for developing flexible and loosely coupled Web applications. The MVC pattern helps separate different aspects of the application, such as input logic, business logic, and UI logic, while providing loose coupling between all these elements.
7.2. Describe the workflow of DispatcherServlet
The workflow of DispatcherServlet can be illustrated by a diagram:
A HTTP request is sent to the server and the request is captured by the front-end controller DispatcherServlet.
DispatcherServlet parses the requested URL according to the configuration in-servlet.xml to get the request resource identifier (URI). Then, according to the URI, call HandlerMapping to get all the related objects (including the Handler object and the interceptor corresponding to the Handler object) of the Handler configuration, and finally return in the form of a HandlerExecutionChain object.
DispatcherServlet selects an appropriate Handler based on the obtained HandlerAdapter. (note: if the HandlerAdapter is successfully obtained, the execution of the interceptor's preHandler (...) will begin at this time. Method).
Extract the model data from Request, populate the Handler input parameters, and start executing Handler (Controller). In the process of filling in Handler parameters, depending on your configuration, Spring will do some extra work for you:
HttpMessageConveter: converts the request message (such as Json, xml, and so on) into an object and converts the object into the specified response information.
Data conversion: data conversion is performed on request messages. Such as String conversion to Integer, Double and so on.
Data radicalization: data formatting of the request message. Such as converting a string to a formatted number or formatting a date, etc.
Data validation: verify the validity of the data (length, format, etc.), and the verification results are stored in BindingResult or Error.
After the execution of Handler (Controller) is completed, a ModelAndView object is returned to DispatcherServlet
Based on the returned ModelAndView, select a suitable ViewResolver (which must be a ViewResolver that is already registered in the Spring container) and return it to DispatcherServlet.
ViewResolver combines Model and View to render the view.
The view is responsible for returning the rendered results to the client.
7.3. Introduce WebApplicationContext.
WebApplicationContext is an extension of ApplicationContext. It has some additional functionality required by Web applications. It differs from a normal ApplicationContext in its ability to parse topics and decide which servlet to associate with.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.