1. Introduction to Spring Framework
What is Spring?
Spring is an open source lightweight application development framework. The purpose is to simplify enterprise-level application development and reduce intrusion
The IOC and AOP applications provided by Spring can minimize the coupling of components, that is, decoupling, to facilitate future maintenance and upgrades of the system
Spring provides an overall solution for the system. In addition to the functions it provides, developers can also integrate applications with third-party frameworks and technologies, and can freely choose which technology to use for development
2. Container and Bean management
Introduction to Spring container
In Spring, any java class and javaBean are treated as beans. These beans are managed and applied through the container.
Spring container implements IOC and AOP mechanisms. These mechanisms can simplify the creation of Bean objects and the decoupling between Bean objects.
Spring container has two BeanFactory and ApplicationContext Type
(What is javaBean: a simple and standardized java object; when to use Spring: You can use it when you need to manage javaBean objects. Spring is one of the simplest object management solutions)
Instantiation of Spring container
ApplicationContext inherits from the BeanFactory interface and has more enterprise-level methods. It is recommended to use this type. The instantiation method is as follows:
//Load the configuration file instantiation in the file system
String conf = "C:\applicationContext.xml";
ApplicationContext ac = new FileSystemXmlApplicationContext(conf);
//Load the configuration file instantiation under the project classpath
String conf = "applicationContext.xml";
ApplicationContext ac = new ClassPathXmlApplicationContext(conf);
The use of Spring container
In essence, BeanFactory and ApplicationContext are just a high-level factory interface that maintains Bean definitions and interdependencies. We can access the bean definition through BeanFactory and ApplicationContext
First add the Bean definition in the container configuration file applicationContext.xml
Then after creating the BeanFactory and ApplicationContext container objects, call the getBean() method to obtain the instance of the Bean [getBean("identifier")] Instancing of the Bean There are three ways for the Spring container to create Bean objects: -Use the constructor to instantiate (The id or name attribute is used to specify the Bean name and is used to find the Bean object from Spring; class is used to specify the Bean type and will automatically call the parameterless constructor to create the object) -Use static factory method to instantiate (The id attribute is used to specify the Bean name, the class attribute is used to specify the factory type, and the factory-method attribute is used to specify the method for creating Bean objects in the factory. Methods that must be decorated with static) -Use the instance factory method to instantiate (id is used to specify the bean name, the factory-bean attribute is used to specify the factory Bean object, and the factory-method attribute is used to specify the method of creating the Bean object in the factory) (Tell Spring the object creation rules, Spring Will help you create objects; based on configuration and default rules, reducing code writing) Bean naming Bean name: In the Spring container, each Bean needs to have a name (i.e. identifier). The name can be specified using the id or name attribute of the Bean alias: is a defined Bean, and to add another name reference, you can use Bean scope: Spring container is in When instantiating a bean, you can create Bean objects with the following scopes 1, singleton scope (The above Bean scope can be specified through the scope attribute defined by Bean life cycle callback Specify the initialization callback method: Specify the destruction callback method, only applicable to beans in singleton mode:
In each Spring IOC A bean definition in the container corresponds to an object instance. The default item
configures the instance:
or
2、prototype
One bean definition corresponds to multiple object instances
Configuration instance:
or
3. request
request means that a new bean will be generated for each HTTP request, and the bean is only valid within the current HTTP request
When using request, session, and global session, you must first make the following configuration in the web.xml that initializes the web:
If you are using a web container with Servlet 2.4 and above, then you only need Just add the following ContextListener to the XML declaration file web.xml of the web application:
If it is a web container before Servlet2.4, then you have to use an implementation of javax.servlet.Filter :
Then you can configure the scope of the bean:
4, session
session scope means that a new bean will be generated for each HTTP request, and the bean will only be generated during the current HTTP request. Valid within the session (in an HTTPSession, one bean definition corresponds to one instance, limited to the Web environment)
Configuration instance:
The premise is the same as the request configuration instance. After configuring the web startup file, you can configure it as follows:
5、global session
In a global HTTPSession, one bean definition corresponds to one instance, which is only meaningful in portlet-based Web applications. The Portlet specification defines the concept of global Session
Configuration instance:
and The premise of request configuration instance is the same. After configuring the web startup file, you can configure it as follows:
The default-init-method attribute in the top-level
The default-destroy-method attribute in the top-level
beans>
Bean delayed instantiation
The default behavior implemented in ApplicationContext is to instantiate all singleton beans in advance at startup
If you don’t want to To allow a singleton bean to be instantiated in advance when the ApplicationContext is initialized, you can use the lazy-init = "true" attribute of the
A lazy-initialized bean will be instantiated the first time it is used
In the top-level
Specify bean dependencies
When a bean has a dependency on another bean, you can use the depends-on attribute of the
When a bean is dependent on multiple When a bean has a dependency relationship, the depends-on attribute can specify multiple bean names, separated by commas
3. Container IOC application
IOC concept
The full name of IOC is Inversion of Control, translated as inversion of control;
IOC refers to the reversal of the acquisition method of objects in the program, from the original new method to creation and injection by a third-party framework. Third-party frameworks generally specify which specific implementation to inject through configuration, thereby reducing the coupling between objects
IOC can be divided into two types: dependency injection DI and dependency lookup depending on the implementation method
Spring container uses DI to implement IOC control. IOC is the foundation and core of Spring container
DI concept
The full name of DI is Dependency Injection, which is translated Injecting dependencies
The basic principle of DI is to connect objects that work together and have relationships through constructor parameters or method parameters. Therefore, the job of the container is to inject those dependencies when creating a bean
IOC is an idea, and DI is the main technical way to realize IOC
DI has two main injection methods, namely Setter injection and constructor injection
Setterr injection
After instantiating a bean by calling the parameterless constructor or parameterless static factory method, and calling the setter method of the bean, setter injection can be achieved
public class JDBCDataSource{
private String driver;
public void setDriver(String driver){
try{
Class .forName(driver);
this.driver = driver;
}catch(Exception e){
throw new RuntimeException(e);
}
}
//Other codes....
}
In the container xml configuration, configure the injection parameters
Constructor injection
Constructor-based injection is done by calling a constructor with parameters It is implemented by the container. When the bean is instantiated, the container executes the corresponding constructor according to the parameter type
public class OracleUserDAO implements UserDAO{
private JDBCDataSource dataSource;
public OracleUserDAO(JDBCDataSource dataSource){
this.dataSource = dataSource;
}
//Other code...
}
Specify injection according to constructor parameter index
< ;constructor-arg index = "0" ref = "dataSource"/>
Autowiring
Spring IOC The container can automatically assemble (autowire) the association between cooperating beans. Autowire can be set for a single bean. The convenience of autowire is to reduce the injection configuration of xml
In the xml configuration file, you can Use the autowire attribute in the ;bean/> element to specify automatic assembly rules. There are five types of values.
The attribute value is no:Autowire is prohibited, and the default value is ;
The attribute value is byName:Automatically assemble based on the attribute name. This option will check the container and find a bean that is exactly the same as the attribute based on the name, and automatically assemble it with the attribute;
The attribute value is byType: If there is a bean with the same type as the specified attribute in the container, it will be automatically assembled with the attribute;
The attribute value is constructor: is similar to byType, except that it is applied to the constructor parameter;
The attribute value is autodetect:Determine whether to use the constructor or byType method for automatic detection through the bean class Assembly, if a default constructor is found, the byType method will be used
Configuration example:
In the above configuration, if there is a method Setter method that receives the UserDao type in UserService, Spring can automatically inject the userDAO object into it
The above is the detailed content of Spring IOC container. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In 2023, AI technology has become a hot topic and has a huge impact on various industries, especially in the programming field. People are increasingly aware of the importance of AI technology, and the Spring community is no exception. With the continuous advancement of GenAI (General Artificial Intelligence) technology, it has become crucial and urgent to simplify the creation of applications with AI functions. Against this background, "SpringAI" emerged, aiming to simplify the process of developing AI functional applications, making it simple and intuitive and avoiding unnecessary complexity. Through "SpringAI", developers can more easily build applications with AI functions, making them easier to use and operate.

As an industry leader, Spring+AI provides leading solutions for various industries through its powerful, flexible API and advanced functions. In this topic, we will delve into the application examples of Spring+AI in various fields. Each case will show how Spring+AI meets specific needs, achieves goals, and extends these LESSONSLEARNED to a wider range of applications. I hope this topic can inspire you to understand and utilize the infinite possibilities of Spring+AI more deeply. The Spring framework has a history of more than 20 years in the field of software development, and it has been 10 years since the Spring Boot 1.0 version was released. Now, no one can dispute that Spring

How to implement spring programmatic transactions: 1. Use TransactionTemplate; 2. Use TransactionCallback and TransactionCallbackWithoutResult; 3. Use Transactional annotations; 4. Use TransactionTemplate in combination with @Transactional; 5. Customize the transaction manager.

According to Huawei’s official news, the Open Atomic Developer Conference, with the theme of “Everything for Developers”, was held in Wuxi for two days, from December 16 to 17. The conference was led by the Open Atomic Open Source Foundation, Huawei, and Inspur. , DaoCloud, Xieyun, Qingyun, Hurricane Engine, as well as the OpenSDV Open Source Alliance, openEuler community, OpenCloudOS community and other member units jointly initiated the construction of the AtomHub Trusted Mirror Center, which is officially open for public testing. AtomHub adheres to the concepts of co-construction, co-governance, and sharing, and aims to provide open source organizations and developers with a neutral, open and co-constructed trusted open source container mirror center. In view of the instability and uncontrollability of image warehouses such as DockerHub, and some

How to set the transaction isolation level in Spring: 1. Use the @Transactional annotation; 2. Set it in the Spring configuration file; 3. Use PlatformTransactionManager; 4. Set it in the Java configuration class. Detailed introduction: 1. Use the @Transactional annotation, add the @Transactional annotation to the class or method that requires transaction management, and set the isolation level in the attribute; 2. In the Spring configuration file, etc.

Detailed explanation of the Bean acquisition method in Spring In the Spring framework, Bean acquisition is a very important part. In applications, we often need to use dependency injection or dynamically obtain instances of beans. This article will introduce in detail how to obtain beans in Spring and give specific code examples. Obtaining the Bean@Component annotation through the @Component annotation is one of the commonly used annotations in the Spring framework. We can do this by adding @Compone on the class

Steps of spring configuration file: 1. Create XML configuration file; 2. Add necessary dependencies; 3. Configure data source; 4. Define beans; 5. Configure other components; 6. Inject dependencies; 7. Configure environment; 8. Enable Automatic assembly; 9. Deploy the application; 10. Start the application. Detailed introduction: 1. Create an XML configuration file and create an XML file in the resource directory of the project. This file will contain Spring configuration information; 2. Add necessary dependencies, etc.

In back-end management systems, access permission control is usually required to limit different users' ability to access interfaces. If a user lacks specific permissions, he or she cannot access certain interfaces. This article will use the waynboot-mall project as an example to introduce how common back-end management systems introduce the permission control framework SpringSecurity. The outline is as follows: waynboot-mall project address: https://github.com/wayn111/waynboot-mall 1. What is SpringSecurity? SpringSecurity is an open source project based on the Spring framework, aiming to provide powerful and flexible security for Java applications.
