By Taosu
IoC (Inverse of Control) is a design concept where the control originally exercised within a program to manually create objects is delegated to a framework like Spring. In other languages, IoC is also applied and is not unique to Spring.
An IoC container is the carrier of Spring to implement IoC. IoC container is actually a Map (key, value) that stores various objects. The dependencies between objects are given to the IoC container to manage, and the IoC container completes the injection of objects. This can greatly simplify the applications' development and free the applications from complex dependencies. An IoC container acts like a factory, and when we need to create an object, we only need to configure the configuration files and annotations, and we don't need to consider how the objects are created.
From the perspective of a container, DI (Dependency Injection) refers to the process of injecting other objects that one object depends on during its creation into the object.
AOP (Aspect-Oriented Programming) enables encapsulation of logic and responsibilities that are unrelated to the core businesses but commonly called across business modules, including transaction processing, log management, and access control. This reduces the duplication of code in the system, decreases the coupling between modules, and facilitates future scalability and maintainability.
Spring AOP operates based on the dynamic proxy. If the target object implements an interface, Spring AOP will utilize JDKProxy to create a proxy object. However, if the object does not implement any interface, it cannot use JDK Proxy to be proxied. In this case, Spring AOP will resort to Cglib dynamic proxy, which is built on ASM framework byte stream. When this occurs, Spring AOP will use Cglib to generate a subclass of the target object to serve as the proxy.
Summary: The lifecycle of a singleton object is the same as that of a container.
Birth: Spring framework creates the object for us when we use objects
Alive: The object is alive as long as it is in use
Death: When an object is not used for a long time and no other objects are referenced, it is recycled by Java's garbage collection mechanism
The IoC container initialization process which loads Bean:
@Overridepublic void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { // Step 1: Pre-processing before refreshing prepareRefresh(); //Step 2: Get BeanFactory and register it with BeanDefitionRegistry ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // Step 3: Preparation for loading BeanFactory (BeanFactory makes some settings, such as the class loader of context.) prepareBeanFactory(beanFactory); try { // Step 4: Post-preparation work after completing the preliminary setup of the BeanFactory postProcessBeanFactory(beanFactory); // Step 5: Instantiate BeanFactoryPostProcessor interface Bean invokeBeanFactoryPostProcessors(beanFactory); // Step 6: Register the BeanPostProcessor. After the bean is created, execute registerBeanPostProcessors(beanFactory); // Step 7:Initialize the MessageSource component (for internationalization, message binding, message parsing); initMessageSource(); // Step 8: Register the initialization event dispatcher initApplicationEventMulticaster(); // Step 9: Override this method in subclasses to customize the logic when the container is refreshed onRefresh(); // Step 10:Register the listener of the application. That is, register and implement the listener interfaced by ApplicationListener registerListeners(); //Step 11: Initialize all remaining non-lazy loading singleton beans. Initialize and create a non-lazy loading singleton Bean instance (no attribute set) finishBeanFactoryInitialization(beanFactory); //Step 12: Complete context refresh. It is mainly to call the onRefresh() method of the LifecycleProcessor to complete the creation of finishRefresh(); }...}
Summary:
Affecting multiple Beans
Affecting a single Bean
Name | Scope |
---|---|
singleton | Singleton object, the default value scope |
prototype | Each fetch creates a new Bean instance |
request | Each HTTP request results in a new Bean that is valid only within the current HTTP request |
session | In one HTTP session, the container will return the same instance |
global-session | Store the object in the session domain of the web project cluster. If no cluster exists, the global session is equivalent to the session |
The default scope is Singleton. When multi-thread accessing the same Bean, there will be thread security risks.
Each thread has its own ThreadLocalMap class object, which can keep the thread's objects in it. Each thread can correctly access its own objects.
Take a common ThreadLocal static instance as the key, save the references of different objects to the ThreadLocalMap of different threads, and then obtain the object saved by one's own thread through the get() method of this static ThreadLocal instance everywhere the thread executes, thus avoiding the trouble of passing this object as a parameter.
Circular dependency is actually a circular reference, that is, two or more Beans hold each other and eventually form a closed loop. For example, A depends on B, and B depends on A. Circular dependencies in Spring include:
Among them, the circular dependency problem of the constructor cannot be solved. When solving the circular dependency of properties, lazy loading can be used, and Spring uses the method of exposing objects in advance.
When Spring starts, it will parse and convert all bean information (including XML and annotations) into BeanDefinition that Spring can recognize and store it in Hashmap for the following initialization, and then process each BeanDefinition. The initialization of ordinary Beans is performed during the container startup initialization phase, while the bean decorated by lazy-init=true is triggered when context.getBean() is triggered from the container for the first time.
@Component: general-purpose annotations. You can label any class as a Spring component.
@Service: used at the business logic layer (service layer)
@Repository: used at the data access layer (dao layer)
@Controller: used at the presentation layer, the declaration of the controller (controller layer)
@Autowired: assemble and inject by type by default.
@Qualifier: You can change to name
@Resource: assemble and inject by name by default. JDK annotations have been deprecated in the new version.
The use of @Autowired simplifies our development.
It implements AutowiredAnnotationBeanPostProcessor class. This class implements the Spring framework's extended interfaces.
It implements BeanFactoryAware interface to hold its internal BeanFactory (so we can easily get the dependent Bean).
It implements the MergedBeanDefinitionPostProcessor interface, instantiates the Bean before getting the @Autowired information, and caches it.
It implements the postProcessPropertyValues interface, instantiates the Bean, and retrieves the annotation information from the cache. Through reflection, dependent objects are set into the properties of the Bean.
@SpringBootApplicationpublic class JpaApplication { public static void main(String[] args) { SpringApplication.run(JpaApplication.class, args); }}
@SpringBootApplication annotation is equivalent to the following three annotations:
Among the above, @EnableAutoConfiguration
is the key (enable automatic configuration). The inside actually loads the information of the META-INF/spring.factories
file, filters out the data with EnableAutoConfiguration
as the key, and loads it into the IoC container to realize the automatic configuration feature!
It mainly loads the @SpringBootApplication annotation main configuration class. The main feature of this @SpringBootApplication annotation main configuration class is that SpringBoot opens an automatic configuration feature of @ EnableAutoConfiguration annotation.
It mainly uses the EnableAutoConfigurationImportSelector to import some components into the Spring container.
@Import(EnableAutoConfigurationImportSelector.class)public @interface EnableAutoConfiguration
@Controller declares that this class is a Controller in SpringMVC. @RequestMapping is used to map web requests. @ResponseBody supports placing the return value in the response instead of a page. Usually, the user returns JSON data. @RequestBodyallows the parameters of the request to be in the request body instead of directly connecting after the address. @PathVariable is used to receive the path declared by the path parameter. @RequestMapping("/hello/{name}") and put the annotation before the parameter to obtain the value, which is usually used as the interface implementation method of the Restful.
@Insert: insert SQL. The syntax is the same as XML insert SQL. @Select : query SQL. The syntax is the same as XML select SQL. @Update : update SQL. The syntax is the same as XML update SQL. @Delete : delete SQL. The syntax is the same as XML delete SQL. @Param: input parameters @Results: set the result set @Result: the result @ResultMap: reference result set @SelectKey: get the latest insert ID
Simply put, #{} is precompiled and safe.
**{}
is not precompiled and just takes the value of the variable, so it is not safe and can involve SQL injection. When you write mapping statements for MyBatis, try to use the format **"#{xxx} "**
. If you need to dynamically pass in the table name and column name, you also need to make the following modifications: add the attribute **statementType="STATEMENT"**
, and change the value of all variables in SQL to ****{}
without precompilation. It only takes the value of the variable, which is unsafe and involves SQL injection. When you write mapping statements for MyBatis, try to use the format **"#{xxx} "**
. If you need to dynamically pass in the table name and column name, you also need to make the following modifications: add the attribute **statementType="STATEMENT"**
, and change the values of all variables in SQL to **{xxxx}**
Hibernate is an open-source object-relational mapping framework, which provides a very lightweight object encapsulation for JDBC to map objects to database tables. is a fully automated, fully object-oriented persistent layer framework.
MyBatis is an open-source object-relational mapping framework, formerly known as iBATIS, which was renamed after Google took over in 2010. It is a semi-automated persistent layer framework.
During the project development process, in terms of speed:
In Hibernate development, SQL statements have been encapsulated and can be used directly to speed up system development.
MyBatis is semi-automated, and SQL needs to be completed manually, which is a little cumbersome.
However, nothing is absolute. In the context of massive and complex system projects where complex statements abound, Hibernate may not be the ideal solution.
Hibernate automatically generates SQL, and some statements are more cumbersome, which consume more performance.
MyBatis needs manual writing of SQL, which can avoid unnecessary queries and improve system performance.
Hibernate is a complete object-relational mapping framework. During the development process, you do not need to focus on the underlying implementation details, but rather, you can concentrate on managing objects.
MyBatis needs you to manage mappings by yourself.
@EnableTransactionManagement @Transactional
Notes:
① Do not process time-consuming tasks in transaction functions, which will result in long-term possession of database connections.
② Do not process irrelevant business in the transaction functions to prevent transaction rollback due to exceptions.
Singleton design pattern: Beans in Spring are singleton by default.
Factory design pattern: Spring uses the factory pattern to create Bean objects through BeanFactory and ApplicationContext.
Proxy design pattern: The implementation of Spring AOP.
Observer pattern: The Spring event-driven model is one classic application of observer pattern.
Adapter pattern: The enhancement or notification (Advice) of Spring AOP uses the adapter pattern. Spring MVC also uses adapter pattern to adapt to Controller.
Disclaimer: The views expressed herein are for reference only and don't necessarily represent the official views of Alibaba Cloud.
Interview Questions We've Learned Over the Years: Multi-threading
1,062 posts | 262 followers
FollowAlibaba Cloud Community - May 6, 2024
Alibaba Cloud Community - July 29, 2024
Alibaba Cloud Community - May 8, 2024
Alibaba Cloud Community - May 3, 2024
Alibaba Cloud Community - May 1, 2024
Alibaba Cloud Community - July 9, 2024
1,062 posts | 262 followers
FollowProvides a control plane to allow users to manage Kubernetes clusters that run based on different infrastructure resources
Learn MoreA secure image hosting platform providing containerized image lifecycle management
Learn MoreAlibaba Cloud Container Service for Kubernetes is a fully managed cloud container management service that supports native Kubernetes and integrates with other Alibaba Cloud products.
Learn MoreMulti-source metrics are aggregated to monitor the status of your business and services in real time.
Learn MoreMore Posts by Alibaba Cloud Community