Table of contents
The difference between BeanFactory and ApplicationContext
1. What is Spring
spring official website: spring.io
Its ecology is very perfect
Generally speaking, Spring refers to the Spring Framework (Spring Framework), which is an open source framework that supports a wide range of application scenarios and makes Java enterprise application development easier.
Spring Framework is the most basic project in the Spring ecosystem and the foundation of other projects
Core: Spring is an IoC container that contains many tools and methods
So what is an IoC container?
Container: List/Map=>data storage container, tomcat=>web container, etc. that I learned before are all containers
Spring=>IoC container
IoC
IoC: Inversion of Control control inversion, Spring is an inversion of control container
So what exactly is IoC?
This starts with the current situation of our Java code writing. In traditional programming, the coupling between objects is relatively high.
Let's write an example, the Test class depends on the A class to complete the task, and A depends on B to complete the task
Create class A
The A object is dependent on the B object, so an error will be reported
plus class B
At this time, class A no longer reports an error
That is, when object A wants to use object B, it needs to create a new object B. At this time, object A has control over object B. When the party is using it, it can set B to null and it will be recycled.
A depends on B, so when the construction method of the B object changes, the A object must also be changed
When the construction method in B is changed, A of newB must also be changed, otherwise an error will be reported
after change
NewA's Test also needs to be changed
It can be found that when the bottom layer changes, the entire call chain needs to change
This reflects the problem of a relatively high degree of coupling between codes. How to solve it?
We write a decoupled way of writing
At this point we change the constructor of B
The first few classes will not report an error, but the test class that provides it reports an error
This approach achieves decoupling
Traditional way: Test depends on A, A depends on B
Decoupling method: B passes into A, A passes into Test
is a reverse process
The life cycle of these classes is not controlled by dependent classes
Summarize:
Solution: Decoupling, when using objects, do not actively new objects, and switch to external acquisition
Even if the parameters of the lower class are changed, the current class itself does not need to be changed, which is the decoupling of the program
IoC is responsible for the creation of objects and initialization of a series of tasks. The created or managed objects are collectively referred to as Beans in the IoC container.
The core idea of IoC: the control of object creation is transferred from the program to the outside. This idea is called inversion of control.
A only uses the B object, does not perform the new object operation, just uses. Who creates the B object A does not care
At this point, the A object has no control over the B object. The control is handed over, which is the inversion of control!
Back to the theme of Spring, it is an IoC container that contains many method tools, that is, Spring provides an IoC container to act as the "external" in IoC thinking, it has the right to create and destroy objects, and it has storage Objects and Capabilities to Get Objects
Core functions: store objects into containers, and take objects out of containers
What are the benefits of using Spring to access objects?
Putting the object in the container is equivalent to making all the tools that may be used in the future and putting them in the warehouse. When needed, take them out and use them, and put them back into the warehouse when they are used up. The new object method will be recycled when it is empty after use. To use Have to re-new.
There is also a concept that needs to be mentioned, Dependency Injection, or DI for short, means dependency injection
Dependency injection: During the running of the IoC container, a certain dependency is dynamically injected into the object.
It can be seen that IoC is a guiding ideology, and DI is its specific implementation.
2. Spring creation and use
Create Spring
Creating a Spring project is divided into three steps
1. Create a normal Maven project
2. Add Spring framework support
3. Add startup class
1. Create a normal Maven project
This means that the project has been initialized
2. Add Spring dependency
It is necessary to configure the domestic source, otherwise the download will be very slow
Need to use the support of the major version number 5 and jdk to match
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.26</version>
</dependency>
then click refresh
Add dependency successfully
3. Create a startup class
Next we store the Bean object in Spring
access bean
1. Create Bean
Bean: If it is used many times in Java, it is called Bean
2. Store the Bean in the Spring container
Configure Bean information through Spring's configuration file
3. Get Bean from Spring
Get the Spring (context) object first, using ClassPathXmlApplicationContext
The ClassPathXmlApplicationContext class implements the ApplicationContext interface
ClassPathXmlApplicationContext belongs to the subclass of ApplicationContext, has all the functions of ApplicationContext, and obtains all bean containers through xml configuration
Note that the path in "" must be written correctly, corresponding to the .xml file under resourses, otherwise the bean we set cannot be found
Then you can get the bean
The content of this parameter must be the same as the id configured in .xml to get the bean
result:
Get the bean object and use it without new object
There are two other ways to get it:
This process is DI implemented through code, which dynamically injects dependencies into objects!
BeanFactory can also get the context of Spring
It can be seen that Application Context is also a subtype of it, which is an extension of its function
public class Application2 {
public static void main(String[] args) {
//1.得到spring上下文对象
BeanFactory beanFactory =
//不推荐使用,是因为早期时内存珍贵,现在内存价格低廉.
//特征:省内存,调用时加载初始化bean到spring容器,效率不高!
new XmlBeanFactory(new ClassPathResource("spring-config.xml"));
//2.从容器中获取对象
//第一种获取方式:这个写法是有问题的,如果本身是"null",强转会出错
Student s2 = (Student) beanFactory.getBean("student");
//3.使用对象
s2.sayHi();
}
}
The difference between BeanFactory and ApplicationContext
So what is the difference between these two methods?
Let's create another class
Configure Bean information
We just call this line of code that gets the context
we can find out that:
ApplicationContext is one-time loading, which consumes more memory, but subsequent reading is very fast, and all beans in spring will be initialized and all instantiated into spring!! Hungry man mode
Beanfactory does not, it uses lazy loading, and only when the get bean is executed will the corresponding bean be loaded!!!
In terms of inheritance relationship:
Spring has two top-level interfaces, BeanFactory and ApplicationContext. BeanFactory provides basic access to containers, and ApplicationContext is a subclass of BeanFactory. In addition to inheriting BeanFactory, it also has other features, adding support for internationalization, resources Access support, and support for event propagation, etc.
3. Summary
1. Create a Spring project
Create a Maven project
Add Spring-context dependency
Create a startup class
2. Storage Bean
Create a Bean object
Through the Spring configuration file (spring-config.xml)
<bean id="bean name" class="package name + class name"></bean>
3. Read Bean
Get the Spring context (BeanFactory and ApplicationContext)
Get the Bean object through the Spring object.getBean() method (this process is DI)
use beans