What is the difference between BeanFactory and ApplicationContext
A BeanFactory can be understood as a factory class containing a collection of beans. BeanFactory contains the definition of the kind of bean to instantiate the corresponding bean when a client request is received.
BeanFactory can also generate relationships between collaborating classes when instantiating objects. This move frees the bean itself from the configuration of the bean client. The BeanFactory also contains control of the bean lifecycle, calling client-side initialization methods and destruction methods.
On the surface, the application context, like the bean factory, has the ability to define beans, set bean associations, and distribute beans based on requests. But application context offers other features on top of that.
Text messages with internationalization support are provided
Unified way of reading resource files
Events for beans that have been registered in the listener
Spring bean lifecycle
The Spring Bean lifecycle is simple and easy to understand. 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 the associated destruct operation needs to be performed and removed from the bean container.
The Spring bean factory is responsible for managing the lifecycle of beans that are created in the spring container. The life cycle of a bean consists of two sets of callback methods.
The callback method to be called after initialization.
The callback method called before the destruction.
The Spring framework provides the following four ways to manage bean lifecycle events.
InitializingBean and DisposableBean callback interfaces
Other Aware interfaces for specific behaviors
Custom init() method and destroy() method in the Bean configuration file
@PostConstruct and @PreDestroy annotation methods
How Spring IOC is implemented
The org.springframework.beans package and the org.springframework.context package in Spring form the basis of the Spring Framework IoC container.
The BeanFactory interface provides an advanced configuration mechanism that makes configuration of any type of object possible. The ApplicationContex interface extends the BeanFactory (which is a sub-interface), adding additional functionality to the BeanFactory, such as easier integration with Spring's AOP, and also providing mechanisms for handling message resources (for internationalization), event propagation, and application layer-specific configurations, such as WebApplicationContext for web applications.
The org.springframework.beans.factory.BeanFactory is a concrete implementation of the Spring IoC container that is used to wrap and manage the various beans mentioned earlier. The BeanFactory interface is the core interface of the Spring IoC container.
Talking about Spring AOP
Cut-oriented programming, in our applications, often requires doing things that are not related to the core business, for example, to record all updateThe method's execution time, time, operator, etc. are recorded in the log. With spring's AOP techniques, it is possible to modify the update without modifying the of the code to complete the requirement.
Spring AOP implementation principles
There are two main approaches to dynamic proxies in Spring AOP, JDK dynamic proxies and CGLIB dynamic proxies. The JDK dynamic proxy receives the proxied class through reflection and requires that the proxied class must implement an interface. The core of the JDK dynamic proxy is the InvocationHandler interface and the Proxy class.
If the target class does not implement an interface, then Spring AOP will choose to use CGLIB to dynamically proxy the target class. CGLIB (Code Generation Library), is a code generation class library that can dynamically generate subclasses of a class at runtime. Note that CGLIB is a dynamic proxy by inheritance, so if a class is marked as final, then it cannot use CGLIB as a dynamic proxy.
Dynamic proxies (cglib vs. JDK)
JDK Dynamic proxy classes and delegate classes need to both implement the same interface. This means that only classes that implement an interface can use the Java dynamic proxy mechanism. However, the fact is that not all classes you encounter in use will give you an implementation of an interface. Therefore, the mechanism cannot be used for classes that do not implement an interface. CGLIB, on the other hand, enables dynamic proxying of classes.
Spring transaction implementation
By programmatic transactions we mean implementing transactions by coding, i.e., similar to JDBC programming for transaction management.
2. Declarative transaction management approach
Declarative transaction management can be implemented in two ways: an xml configuration file-based approach; and a real @Transaction annotation on business methods to apply transaction rules to the business logic
The underlying principles of Spring transactions
a. Division of processing units - IOC
Since the problem solved by spring is local transaction processing for a single database, the specific implementation of the prime minister divided the transaction processing unit with the IOC in spring. And various configurations for transactions are put into the ioc container (setting up the transaction manager, setting up the propagation characteristics of transactions and the isolation mechanism).
b. AOP intercepts classes that require transaction processing
Spring transaction processing module is through the AOP function to achieve declarative transaction processing, specific operations (such as the configuration and reading of the transaction implementation, the abstraction of the transaction object), using the TransactionProxyFactoryBean interface to use the AOP function to generate proxy proxy objects, through the TransactionInterceptor to complete the interception of the proxy method, the transaction processing functionality woven into the intercepted method. Reads the ioc container transaction configuration attributes into the internal data structure (TransactionAttributeSourceAdvisor) needed for spring transaction processing into a data object represented by TransactionAttribute.
c. Implementation of thing processing (transaction generation, commit, rollback, hang)
spring delegates to a specific transaction processor implementation. An abstraction and adaptation is implemented. Adapted specific transaction processors: DataSource data source support, hibernate data source transaction support, JDO data source transaction support, JPA, JTA data source transaction support. These are supported through the design of PlatformTransactionManager, AbstractPlatforTransaction a series of transaction processing support. A range of TransactionManager is provided for common data source support.
PlatformTransactionManager implements the TransactionInterception interface, allowing it to be combined with the TransactionProxyFactoryBean to form a Spring declarative transaction processing design system.
How to customize annotations to achieve functionality
Creating a custom annotation is similar to creating an interface, but the interface keyword of the annotation needs to start with the @ symbol.
Annotation methods cannot have parameters.
(a) The annotation method return value type is limited to: a basic type, String, Enums, Annotation or an array of these types.
Annotation methods may have default values.
The annotation itself can contain meta-annotations, which are used to annotate other annotations.
Spring MVC runtime flow
1.spring mvc submits all requests to the DispatcherServlet, which delegates the real work of processing the requests to other modules of the application.
2.DispatcherServlet queries one or more HandlerMapping to find the Controller handling the request.
3.The DispatcherServlet asks the request to be submitted to the target Controller
4.After the Controller does the business logic processing, it returns a ModelAndView
5.Dispathcher queries one or more ViewResolver view resolvers to find the view object specified by the ModelAndView object
6.The view object is responsible for rendering back to the client.
Spring MVC startup process
In the web.xml file, the Spring MVC servlet is configured with load-on-startup, so the application starts with
When Spring MVC is initialized, the configured contextConfigLocation is set in the HttpServletBean
property to the Servlet, and then creates a WebApplicationContext in the FrameworkServlet,
The DispatcherServlet initializes the xml file under the classpath of the contextConfigLocation configuration based on the
Spring MVC Total components.
Excerpted from: SpringMVC Source Code Analysis and Practice
What design patterns are used in the Spring framework
Proxy pattern - is used more in AOP and remoting.
Singleton pattern - bean defined in spring configuration file is singleton pattern by default.
Template method - used to solve the problem of code duplication. For example. RestTemplate, JmsTemplate, JpaTemplate.
Front End Controller - Spring provides DispatcherServlet to distribute the requests.
View Helper - Spring provides a series of JSP tags and efficient macros to assist in integrating discrete code into the view.
Dependency Injection - The core concept that runs through the BeanFactory / ApplicationContext interface.
Factory pattern-BeanFactory is used to create instances of objects.
Other Spring products (Srping Boot, Spring Cloud, Spring Secuirity, Spring Data, Spring AMQP, etc.)
Why Choose Netty
1) Simple API usage and low development threshold.
2) Powerful, with pre-programmed codecs and support for a wide range of mainstream protocols.
3) Highly customizable and flexible extensions to the communication framework via ChannelHandler.
4) High performance, by comparing with other mainstream NIO frameworks in the industry, Netty has the best overall performance.
5) Mature and stable, Netty fixes all the JDK NIO bugs that have been found, so business developers do not need to bother with NIO bugs anymore.
6) An active community with a short release iteration cycle, where bugs found can be fixed in a timely manner, while more new features are added.
7) Proven quality through large-scale commercial applications. It has been successfully commercialized in many industries such as Internet, big data, online games, enterprise applications, telecom software, etc., proving that it can fully meet the business applications of different industries.
It is because of these advantages that Netty is gradually becoming the framework of choice for Java NIO programming.
Talking about business, Netty usage scenarios
Building high-performance, low-latency various Java middleware, such as MQ, distributed service frameworks, ESB message buses, etc. Netty is mainly used as a base communication framework to provide high-performance, low-latency communication services.
An underlying communication framework for public or private protocol stacks, e.g. an asynchronous, high-performance WebSocket stack can be built on Netty.
Various domain applications, such as big data, games, etc., Netty is used as a high-performance communication framework for internal modules to distribute, transfer and aggregate data, etc., to achieve high-performance communication between modules.
Native NIO has epoll bug in JDK version 1.7
It causes Selector null polling, which eventually leads to 100% CPU. The official claim is that update 18 of JDK 1.6 fixed the issue, but the problem still exists until JDK 1.7, only the probability of the bug occurring is reduced a bit, it is not fundamentally solved.
What is TCP Sticky Packet/Unpacket
1. The data to be sent is larger than the remaining space size of the TCP send buffer, and unpacking will occur.
2. The data to be sent is larger than the MSS (maximum message length), and TCP will unpack before transmission.
3. The data to be sent is smaller than the size of the TCP send buffer, and TCP will send the data written to the buffer multiple times at once, and sticky packets will occur.
4. The application layer at the receiving data side does not read the data in the receiving buffer in time, and sticky packets will occur.
TCP sticky packet/unpacket solution
1, the sender adds a packet header to each packet, which should contain at least the length of the packet, so that the receiver will know the actual length of each packet by reading the length field in the packet header after receiving the data.
2, the sender will encapsulate each packet to a fixed length (not enough can be filled by complementary zeros), so that the receiver will naturally split each packet each time it reads the fixed-length data from the receive buffer.
3, you can set a boundary between packets, such as adding a special symbol, so that the receiving end can split the different packets by this boundary.
Netty thread model
First, Netty uses EventLoop to handle read and write events on a connection, and all requests on a connection are guaranteed to be handled in one EventLoop, and there is only one Thread in an EventLoop, so it is also implemented that all events on a connection will only be executed in one thread. An EventLoopGroup contains multiple EventLoops, and an EventLoop can be treated as a thread in the Reactor thread model, while an EventLoopGroup is similar to an ExecutorService
Source: Jane's Book
Copyright belongs to the author. For commercial reprints, please contact the author for permission, and for non-commercial reprints, please cite the source.
Talking about Netty's zero copy
"Zero-copy" means that the CPU does not need to consume resources for copying data between memories during computer operations. And it usually refers to the way a computer sends files over a network without copying the file contents to User Space but directly to the network in Kernel Space.
Netty internal execution flow
Netty's receive and send ByteBuffer uses DIRECT BUFFERS to use direct off-heap memory for socket reads and writes, eliminating the need for a secondary copy of the byte buffer. If you use traditional heap memory (HEAP BUFFERS) for socket reads and writes, the JVM will make a copy of the heap memory Buffer into direct memory before writing to the socket. Compared to off-heap direct memory, the message has an extra copy of the memory in the buffer during sending.
Netty provides a combinatorial Buffer object that aggregates multiple ByteBuffer objects. Users can operate on the combinatorial Buffer as easily as on a Buffer, avoiding the traditional way of merging several small Buffer into one large Buffer through memory copy.