This is the 27th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”
❤️ About the author: Hello everyone, I am Xiao Xu Zhu. Java field quality creator 🏆, CSDN blog expert certification 🏆, Huawei Cloud enjoy expert certification 🏆
❤️ technology live, the appreciation
❤️ like 👍 collect ⭐ look again, form a habit
Review:
Spring Framework – Understanding the Spring Framework (part 1)
Spring Framework – Understanding IOC (2)
Spring Framework – Understanding AOP (3)
The interviewer’s favorite and most likely question about Spring
Talk about your understanding of Spring
Spring’s official definition:
Spring is a lightweight inversion of Control (IOC) and AOP oriented open source container framework
Spring has some advantages:
1. The coupling between components is reduced and the decoupling between software layers is realized
2. You can use many services provided by the container, such as transaction management, messaging services, etc
3. Containers provide singleton support
4. The container provides AOP technology, which makes it easy to implement functions such as permission interception, runtime monitoring, system logging, and so on
5. Containers provide a number of helper classes to speed up application development
6. Spring provides integration support for mainstream application frameworks, such as Hibernate, Mybatis, Struts2, etc
7. Spring is a low-intrusive design with minimal code contamination
8. Independent of various application servers
9. Spring’s DI mechanism (dependency injection) reduces the complexity of business object replacement
10. The open nature of Spring does not force applications to rely entirely on Spring. Developers are free to choose Spring
Part or all of.
Spring is the spring of programmers.
Start with an understanding of IOC and AOP
Spring Framework – Understanding IOC (2)
Spring Framework – Understanding AOP (3)
Talk about your understanding of IOC
This is a derivative question:
What is IOC? –> Why IOC–> Inversion of control is the inversion of who to whom? What does the IOC container do — how does it differ from the factory model?
What is the IOC
IoC(Inversion of Control), which is an Inversion of class and class dependencies to the container.
There is a net friend describe very apt to IOC: www.zhihu.com/question/48…
Why IOC
- Reduces object creation and management, making code hierarchies clearer.
- Spring’s IOC container is a lightweight container that is non-invasive (doesn’t rely on the container’s API) and doesn’t require special interfaces to be implemented.
- Encourage us to program toward interfaces.
- It reduces the coupling of the code, pushing the coupling parts into the configuration file, and only changing the configuration file if their relationship changes.
Inversion of control is the inversion of who to whom
- Control refers to the control the current object has over its internal members.
- Inversion means that this control is no longer managed by the current object, but by someone else (a class, a third party container)
In traditional Java SE programming, we create objects directly inside the object through new, and the program actively creates dependent objects. IoC has a special container to create these objects, that is, the IoC container controls the creation of objects;
What the IOC container does
The IOC container is essentially a big factory that manages all of our objects and dependencies
- By reflection we can get all the information about a class (member variables, class names, etc.)!
- The relationships between classes are described through configuration files (XML) or annotations
- We can use this configuration information and reflection techniques to build corresponding objects and dependencies
What are the similarities and differences between what IOC does and the factory model
The same point: change the initiative into the passive: the concrete realization of the product (production) is handed over to the factory, and the business logic (customer code) only needs to ask the factory for the product, he does not care about how the factory produces, and what to produce. As long as it conforms to the nature of the product we agreed on before
The difference: IOC no longer requires the program to actively go to new objects. You don’t see new operations, nor do you see factory mode code. The user just needs to focus on the business code.
Talk about your understanding of AOP
This is also a derivative question: What is AOP? How is a simple AOP intended to be implemented?
What is the AOP
Programming for aspects
What can AOP do
You can isolate business logic from system-level services (system-level services like system logs, transactions, permission validation, and so on)
How is a simple AOP intended to be implemented
Implement a business system log slice
1. Define the annotation log
@Target({ElementType.METHOD})
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
/**91: platform statistics **/
int OPERA_TYPE_STATISTICS = 91;
public int operation(a) ;/ / operation code
public String moudle(a) ;/ / module name
public String subMoudle(a);// Submodule name
public String title(a);// Operation instructions
}
Copy the code
2. At the Controller layer, weave in the business methods
@Controller
@ RequestMapping ("/v1.0 / basicstatistics ")
public class StatisticsController {
@Autowired
private StatisticsService statisticsService;
@log (operation= log.opera_type_statistics,title=" View statistics details ", moudle =" platform ", subMoudle =" statistics ")
@RequestMapping("/inquireStatisticsDetailGlobal.json")
@ResponseBody
public ServerResponse<InquireStatisticsDetailGlobalOutput> inquireStatisticsDetailGlobal(a){
returnstatisticsService.inquireStatisticsDetail(); }}Copy the code
Interception processing of the request path – Operation log interception
public class LogHandlerInterceptor implements HandlerInterceptor {
// Call before the request is processed
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
long startTime = System.currentTimeMillis();
request.setAttribute("startTime", startTime);
return true;
}
// After the request is processed, the DispatcherServlet is called before the view returns to render
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
HandlerMethod handler2=(HandlerMethod) handler;
Log log = handler2.getMethod().getAnnotation(Log.class);// Get log object data
System.out.println("Handle log");
}
// execute after the DispatcherServlet renders the corresponding view. Used to clear resources
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
long payTime = System.currentTimeMillis()-(long) request.getAttribute("startTime");// Business processing takes time
System.out.println("AfterCompletion business is processed, resources are cleaned, and back to the front end."); }}Copy the code
Explain the life cycle of Spring beans
The life cycle of Spring beans is straightforward. When a bean instance is initialized, a series of initialization operations need to be performed to reach a usable state. Similarly, when a bean is not being called, it needs to be destructed and removed from the bean container.
The Spring Bean Factory is responsible for managing the life cycle of beans that are created in the Spring container. The Bean life cycle consists of two sets of call back methods.
- The callback method invoked after initialization.
- Destroys the previously called callback method.
The Spring framework provides four ways to manage bean lifecycle events:
-
InitializingBean and DisposableBean callback interfaces
-
Other Aware interfaces for specific behaviors
-
The Custom init() and destroy() methods are in the Bean configuration file
-
@postConstruct and @PreDestroy annotation methods
Examples of code to manage the bean life cycle using the customInit() and customDestroy() methods are as follows:
<beans> <bean id="demoBean" class="com.somnus.task.DemoBean" init-method="customInit" destroy-method="customDestroy"></bean> </beans>
Scope of the Spring Bean
Beans in the Spring container fall into five categories. All scope names are self-explanatory, but to avoid confusion, let’s explain:
- Singleton: This scope of beans is the default. This scope ensures that no matter how many requests are received, there is only one instance of a bean in each container, and the singleton pattern is maintained by the bean Factory itself.
- Prototype: The protoscope is the opposite of the singleton scope, providing one instance for each bean request.
- Request: An instance is created in the scope of the request bean for each network request from the client. After the request completes, the bean is invalidated and collected by the garbage collector.
- Session: Similar to request scope, ensure that there is an instance of a bean in each Session and that the bean is invalidated after the Session expires.
- Global-session: global-session is related to Portlet applications. When your application is deployed to work in a Portlet container, it contains many portlets. If you want to declare that all portlets share global stored variables, the global variables need to be stored in global-session.
The global scope has the same effect as session scope in the Servlet. If you use the 3, 4, and 5 scopes, you need to manually set the proxy
What’s the difference between BeanFactory and ApplicationContext
A BeanFactory can be thought of as a factory class that contains a collection of beans. The BeanFactory contains the definition of a bean to instantiate when a client request is received.
BeanFactory can also generate relationships between collaborating classes when instantiating objects. This frees up the configuration of the bean itself and the bean client. BeanFactory also includes control of the bean lifecycle, calling client-side initialization methods and destruction methods.
The Application Context is a subinterface to the beanFactory and has all the functionality of the beanFactory, but applicationContext provides additional functionality on top of it.
- Text messages that support internationalization are provided
- Unified resource file reading method
- Events for beans that have been registered in listeners
- And the beanFactory is lazy-loaded, creating instances of classes when they are needed, whereas the ApplicationContext loads all singleton beans at initialization
Here are three more common implementations of ApplicationContext:
1, the ClassPathXmlApplicationContext: read the context from the classpath XML configuration files, and generate the context definition. The application context is obtained from the program environment variable
ApplicationContext context = new ClassPathXmlApplicationContext (" bean. XML ");Copy the code
2, FileSystemXmlApplicationContext: from the XML configuration file read the context in the file system.
ApplicationContext context = new FileSystemXmlApplicationContext (" bean. XML ");
XmlWebApplicationContext: The XML file of the Web application reads the context.
Are singleton Beans in the Spring framework thread-safe
The Spring framework does not do anything multithreaded to encapsulate singleton beans. The thread safety and concurrency issues with singleton beans are up to the developer. In practice, however, most Spring beans do not have mutable state (such as Serview and DAO classes), so Spring’s singleton beans are thread-safe to some extent. If your bean has multiple states (such as View Model objects), you’ll need to make your own thread-safe. The simplest solution is to change the scope of polymorphic beans from “Singleton” to “Prototype.”
What is the difference between constructor injection and property injection
- Most dependency injection is supported in the property injection method. If we only need to inject int, string, and long variables, we should not use set method injection. For primitive types, we can set default values for primitive types if we have no injection. Most dependency injection is not supported in constructor injection because the constructor must be called with the correct construction parameters, otherwise an error is reported.
- Property injection does not override the constructor’s value. If we use both constructor injection and set injection on the same variable, the constructor will not override the value injected by the set method. This is obvious because the constructor is called when the object is created.
- There may be no guarantee that a dependency has been injected when using property injection, which means that the object’s dependencies may be incomplete. Constructor injection, on the other hand, does not allow the generation of objects with incomplete dependencies.
- If object A and object B depend on each other during property injection, Spring throws S when object A is created
ObjectCurrentlyInCreationException is unusual, because A before B object is created object cannot be created, and vice versa. So Spring solves the problem of loop dependency with set injection, because object set methods are called before the object is created.
What design patterns are used in the Spring framework
There are a number of design patterns used in the Spring framework, some of which are typical:
- Proxy pattern – used most often in AOP and remoting.
- Singleton – Beans defined in the Spring configuration file default to singleton.
- Template approach – Used to solve code duplication problems. For example.RestTemplate.
JmsTemplate
.JpaTemplate.
- The front controller – Spring provides it
DispatcherServlet ' 'to distribute requests.
- View Helper – Spring provides a series of JSP tags and efficient macros to help integrate scattered code into views.
- Dependency injection – throughout
BeanFactory
/The core concept of the ApplicationContext interface.
- Factory pattern – BeanFactory is used to create instances of objects.
Spring interview questions and answers will be updated from time to time. goodbye