Control inversion / dependency injection in Spring

Posted by akufen on Sat, 26 Feb 2022 15:44:43 +0100

Chapter 1 control inversion / dependency injection in Spring


Add, delete, modify and check.

Pre class test:

Contents of this chapter

Spring: Spring IOC: give the power to create objects to the spring core container. Factory mode

BeanFactory: lazy man

ApplicationContext: hungry man

< bean id="" name="" class="" scope="" >

Three methods of getBean: id type id + type

There are three ways to create objects: 1 The default is to create 2.2 with parameterless construction Use factory static party 3 Example method

Life cycle:

Singleton object: when the container is closed, the object is destroyed

Thread daemon (GC: garbage collection mechanism)

Section 1: Spring

Controls: object creation.

Inversion of control: give the power to create objects to the spring core container.

1. Introduction

Framework: semi - finished software, developed by American technology magna

Spring ecosystem, spring MVC boot cloud data security

SSM : spring springMVC Mybatis

srpringboot cloud

Spring is a lightweight open source framework for layered Java SE/EE application full stack. With IOC (Inverse Of Control) and AOP (Aspect Oriented Programming) as the kernel, spring provides many enterprise application technologies such as presentation layer spring MVC, persistence layer Spring JDBC and business layer affair management, It can also integrate many famous third-party frameworks and class libraries in the world, and gradually become the most used open source framework for Java EE enterprise applications.

MVC model view controller = = = = > three tier architecture service

Model (entity and dao) view (jsp) controller (servlet) - >

Three tier architecture:

Presentation layer: web controller (page Jump), jsp (page)

Persistence layer: dao (data operation)

Business layer: service (business logic)

2. Development history of spring

In 1997, IBM put forward the idea of EJB

In 1998, SUN formulated the development standard specification ejb1 0

In 1999, ejb1 1 release

In 2001, EJB2 0 publish

In 2003, EJB2 1 release

In 2006, EJB3 0 publish

Rod Johnson (father of spring)

Expert One-to-One J2EE Design and Development(2002)

This paper expounds the advantages and solutions of J2EE development and design using EJB

Expert One-to-One J2EE Development without EJB(2004)

This paper expounds the solution of J2EE development without EJB (Spring prototype)

The latest version of spring, spring 5.0 General Edition (GA), was released in September 2017

3. Advantages of spring

servlet calls dao

BookDao bookdao = new BookDaoImpl();

  • Convenient decoupling and simplified development

Through the IoC container provided by Spring, the dependencies between objects can be controlled by Spring to avoid hard coding

Excessive program coupling. Users do not have to write code for the very low-level requirements such as singleton pattern class and attribute file parsing

To focus more on the application of the upper layer.

  • AOP programming support

Through the AOP function of Spring, it is convenient for aspect oriented programming. Many functions that are not easy to be realized with traditional OOP can be realized

Easy to deal with through AOP.

  • Declarative transaction support

It can free us from the monotonous and boring transaction management code and flexibly manage transactions in a declarative way,

Improve development efficiency and quality.

  • Facilitate program testing

Almost all testing work can be carried out in a container independent programming way. Testing is no longer an expensive operation, but easy to use

What you do.

  • Convenient integration of various excellent frameworks

    Spring can reduce the difficulty of using various frameworks and provide direct support for various excellent frameworks (Struts, Hibernate, Hessian, Quartz, etc.).

Microsoft (cult) j + + sunpk (there are many orthodox sects, scattered, everyone listens to everyone, Spring third-party framework, IBM HP EMC universal Yutong, etc.)

The rise of Spring has brought down Microsoft

  • Reduce the difficulty of using Java EE API

Spring has a thin encapsulation layer for Java EE APIs (such as JDBC, JavaMail, remote call, etc.) to make these APIs

The difficulty of use is greatly reduced.

  • Spring source code is a classic learning example

Spring's source code design is exquisite, the structure is clear, and the ingenuity is unique. It everywhere reflects the master's flexible use of Java design patterns

And profound attainments in Java technology. Its source code is undoubtedly an example of best practices in Java technology.

4.Spring architecture



The Spring framework is a layered architecture consisting of seven well-defined modules. The Spring module is built on the core container, which defines the way to create, configure and manage bean s, as shown in Figure 1.

ORM persistence layer framework

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-brxjdwbz-1645880916) (assets / hemwenocpcqvsarj. PNG! Thumbnail)]

Each module (or component) that makes up the Spring framework can exist alone or be implemented jointly with one or more other modules. The functions of each module are as follows:

  • Core container: the core container provides the basic functions of the Spring framework. The main component of the core container is BeanFactory, which is the implementation of the factory pattern. BeanFactory uses the inversion of control (IOC) pattern to separate the configuration and dependency specifications of the application from the actual application code.

  • Spring context: a spring context is a configuration file xml that provides context information to the spring framework. The spring context includes enterprise services, such as JNDI, EJB, e-mail, internationalization, checksum and scheduling capabilities.

  • Spring AOP: through the configuration management feature, the spring AOP module directly integrates aspect oriented programming functions into the spring framework. Therefore, you can easily make any object managed by the spring framework support AOP. The spring AOP module provides transaction management services for objects in spring based applications. By using spring AOP, declarative transaction management can be integrated into applications without relying on EJB components.

  • Spring DAO: the JDBC DAO abstraction layer provides a meaningful exception hierarchy that can be used to manage exception handling and error messages thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the amount of exception code that needs to be written (such as opening and closing connections). The JDBC oriented exceptions of spring DAO follow the general DAO exception hierarchy.

  • Spring ORM: the spring framework inserts several ORM frameworks to provide ORM object relationship tools, including JDO, Hibernate and iBatis SQL Map. All of this follows spring's common transaction and DAO exception hierarchy.

  • Spring Web module: the Web context module is built on the application context module and provides context for web-based applications. Therefore, the spring framework supports integration with Jakarta Struts. The web module also simplifies processing multipart requests and binding request parameters to domain objects.

  • Spring MVC framework: MVC framework is a full-featured MVC implementation for building Web applications. Through the policy interface, the MVC framework becomes highly configurable. MVC accommodates a large number of view technologies, including JSP, Velocity, Tiles, iText and POI.

The functions of the Spring framework can be used in any J2EE server, and most of them are also suitable for unmanaged environments. The core point of Spring is to support reusable business and data access objects that are not bound to specific J2EE services. There is no doubt that such objects can be reused between different J2EE environments (Web or EJB), independent applications and test environments.

Section 2: IOC control inversion of Spring

1. Why Spring

Objective: to reduce the coupling between objects.

Take chestnuts for example:

How to solve this problem? Use factory mode to solve the problem.

The code has not completed our purpose after modification. At this time, if Food is changed to Food1, it still needs to be modified one by one.

How to solve it? Use polymorphism of the interface.

2. Program coupling (see for yourself after class)

Coupling, also known as coupling degree, is a measure of the degree of correlation between modules. The strength of coupling depends on the complexity of the interface between modules, the way of calling modules and how much data is transmitted through the interface. The coupling degree between modules refers to the dependency relationship between modules, including control relationship, call relationship and data transfer relationship. The more connections between modules, the stronger the coupling, and the worse the independence (reducing the coupling can improve the independence). Coupling exists in various fields, not unique in software design, but we only discuss coupling in software engineering. In software engineering, coupling refers to the dependency between objects. The higher the coupling between objects, the higher the maintenance cost. Therefore, the design of objects should minimize the coupling between classes and components. In software design, coupling degree and cohesion degree are usually used as the criteria to measure the degree of module independence. A criterion for dividing modules is high cohesion and low coupling.

It is classified as follows:

(1) Content coupling. When a module directly modifies or operates the data of another module, or a module transfers to another module without normal entry, such coupling is called content coupling. Content coupling is the highest level of coupling and should be avoided.

(2) Common coupling. Two or more modules jointly reference a global data item. This coupling is called common coupling. In a structure with a large number of common coupling, it is very difficult to determine which module assigns a specific value to the global variable.

(3) External coupling. If a group of modules access the same global simple variable instead of the same global data structure, and the information of the global variable is not transmitted through the parameter table, it is called external coupling.

(4) Control coupling. One module transmits a control signal to another module through the interface, and the module receiving the signal performs appropriate actions according to the signal value. This coupling is called control coupling.

(5) Mark coupling. If A module A passes A common parameter to two modules B and C through the interface, it is said that there is A tag coupling between modules B and C.

(6) Data coupling. Data coupling refers to the transfer of data between modules through parameters. Data coupling is the lowest form of coupling. This type of coupling generally exists in the system, because in order to complete some meaningful functions, it is often necessary to take the output data of some modules as the input data of others.

(7) Indirect coupling. There is no direct relationship between the two modules, and the relationship between them is completely realized through the control and call of the main module.

**Summary: * * coupling is an important factor affecting software complexity and design quality. In design, we should adopt the following principles: if there must be coupling between modules, use data coupling as much as possible, use less control coupling, limit the scope of public coupling and avoid content coupling as much as possible.

Cohesion and coupling: cohesion marks the tightness of each element in a module. It is a natural extension of the concept of information concealment and localization. Cohesion is to measure the relationship within the module from the perspective of function. A good cohesion module should do exactly one thing. It describes the functional connections within the module. Coupling is a measure of the interconnection between modules in the software structure. The strength of coupling depends on the complexity of the interface between modules, the point of entering or accessing a module and the data passing through the interface. The program pays attention to low coupling and high cohesion. That is, the elements in the same module should be highly close, but the interdependence between modules is not so close. Cohesion and coupling are closely related. A module with high coupling with other modules means low cohesion, while a module with high cohesion means low coupling with other modules. In software design, we should strive to achieve high cohesion and low coupling.

3. Solution (IOC control reversal)

What is IOC?

Inversion of Control (IoC for short), yes object-oriented programming A design principle in that can be used to reduce the cost of computers code Between Coupling degree . The most common method is called Dependency Injection (DI) and the other is called Dependency Lookup. When using objects, we no longer directly new, but hand over the right to create objects to the core container in the framework. When we need to use objects, we can get them directly from the container.

The idea of IoC has appeared for a long time, but there is no specific implementation. Everyone writes code according to this idea (create their own factory). Later, there was a master Rod Johnson (founder and famous author of Spring Framework) University of Sydney Not only a computer degree, but also a music degree. More surprisingly, before returning to the field of software development, he also received a doctorate in musicology.), I wrote a framework to implement the idea of IoC. Later, this framework was named Spring. (before that, everyone used the Hibernate framework. The Chinese name of this framework is hibernation, and this framework is bulky and highly coupled. Rod Johnson wrote the framework to solve the problem of high coupling similar to hibernate, so he named his framework Spring and told the world that winter has passed and Spring is coming.).

Section III: Construction of spring project

1.1 download jar package

Official website:

Download address:

Now Spring – > ecosystem (family bucket)


(Spring directory structure:)

*Docs: API and development specification.

*LIBS: jar package and source code.

*schema: constraints.

Create the project and import the jar package

1.2 configuring beans XML file
! [insert picture description here](,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAdGVhX3llYXI=,size_20,color_FFFFFF,t_70,g_se,x_16#pic_center)
1.3 write test code and run it

There are two ways to get the creation of Bean objects in the test class.

Refer to the following for the difference between the two interfaces:

Output results, you can observe the creation of objects and the call of methods

2. Details of spring's management of Bean objects

The core components of spring: BeanFactory interface and ApplicationContext interface

The two functions are similar.

2.1 differences between ApplicationContext and BeanFactory interfaces

Structure diagram of classes in spring factory.

BeanFactory interface

Top level interface of Spring container: get Bean object; Manage the relationship between classes (dependencies) BeanFactory is provided by org springframework. beans. factory. BeanFactory interface definition BeanFactory is the implementation of Factory pattern and the core interface of IOC container. Its responsibilities include: instantiating, locating, configuring objects in the application and establishing dependencies between these objects.

The BeanFactory interface contains the following basic methods - ApplicationContext must have, because it is a sub interface, enhanced version

boolean  containsBean(String beanName) Determine whether the factory contains the with the given name bean Definition, if any, return true. 

Object  getBean(String  str)Returns the registered with the given name bean example. according to bean Configuration of, if yes singleton The mode will return a shared instance, otherwise it will return a new instance, if the specified one is not found bean,This method may throw an exception.

Object  getBean(String, Class) Returns a registered with the given name bean Instance and convert to the given class type

Class  getType(String name) Returns the of the given name bean of Class,If the specified is not found bean Instance, exclude NoSuchBeanDefinitionException abnormal

boolean  isSingleton(String) Judge the of a given name bean Define whether it is singleton mode      

String[]  getAliases(String name) Return given bean All aliases of the name

ApplicationContext interface

It is based on BeanFactory and provides application framework services. The new extended functions are as follows: it provides international support for resource access, such as URL and file event transmission, loading multiple configuration files, etc. there are three common implementation classes

ClassPathXmlApplicationContext: - the path of the classpath to load the xml file

FileSystemXmlApplicationContext: loading xml files based on the root path of the project

AnnotationConfigApplicationContext: annotation based configuration. Configuration based on class writing.


import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;

 * @ClassName SpringTest
 * @Description ToDo
 * @Auther teacher Bai
 * @Date 2020/12/19 10:31
public class SpringTest {

    public static void main(String[] args) {
        //This is how you create an object by using your own new object
        //SpringService service = new SpringServiceImpl();

        Use read bean Creating objects in XML
            First, you need to read the bean XML file
            How do you read it?
                1.Use BeanFactory (the top-level interface of spring core container)
                2.Use the sub interface ApplicationContext of BeanFactory (more powerful self interface) commonly used!
         * 1.Use BeanFactory (the top-level interface of spring core container)
         *      ① Read bean XML configuration file
         *          ClassPathResource resource = new ClassPathResource("bean.xml");
         *      ② Read the bean in step ① Information in XML file
         *          XmlBeanFactory factory = new XmlBeanFactory(resource);
         *      ③ Fetch the bean object through the obtained factory
         *          Object service1 = factory.getBean("service1");
        ClassPathResource resource = new ClassPathResource("bean.xml");
        XmlBeanFactory factory = new XmlBeanFactory(resource);
        Object service1 = factory.getBean("service1");
        SpringService service = (SpringServiceImpl) service1;
         * 2.Use the sub interface ApplicationContext of BeanFactory (more powerful self interface) commonly used!
         *         ① Read bean XML configuration file
         *              Use ClassPathXmlApplicationContext to implement the class (bean.xml under the classpath)
         *              ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
         *              Use the FileSystemXmlApplicationContext implementation class to read the file (bean.xml under the file system path)
         *              ApplicationContext context = new FileSystemXmlApplicationContext("E:\\Class notes \ \ qy127 \ \ spring \ \ spring01 IOC and di \ \ spring-02 \ \ SRC \ \ bean xml");
         *         ② Get the bean object through the obtained context
         *              SpringService service1 = (SpringServiceImpl)context.getBean("service1");
        //ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        ApplicationContext context = new FileSystemXmlApplicationContext("E:\\Class notes\\QY127\\spring\\Spring01-IOC and DI\\spring-02\\src\\bean.xml");
        SpringService service1 = (SpringServiceImpl)context.getBean("service1");
Interview questions: BeanFactory and ApplicationContext Differences between:
BeanFactory actually is Spring The top-level interface in the container.
ApplicationContext Is its sub interface.
The time points of creating objects in singleton mode are different:
ApplicationContext: (Hungry man model)As soon as the configuration file is read, the objects configured in the configuration file will be created immediately.
BeanFactory: (Lazy loading/Lazy mode)when getBean("id"),That is, when according to id It is not created until the object is obtained.
2.1.1 use of test functions in spring
    public void test01(){
        ApplicationContext context  = new ClassPathXmlApplicationContext("Spring.xml");
        People bean = context.getBean(People.class);
    We use Junit Tests need to be created each time ApplicationContext  Object is very troublesome, so use Spring The test performance is better and convenient.
A  Import test package
B Add annotations to the test class
public class JavaTest {
    private  ApplicationContext  context;
    private People  p1;
    public void  test(){
        People bean = context.getBean(People.class);
    public void test01(){
2.2 three methods of getbean()

A through bean Get the bean from the id value of the bean tag in the XML file (using the default construction method)

Object p1 = context.getBean("Unique identification id");//What is obtained here is an Object type, which can be converted to the type we need.

B get by type

People bean = context.getBean(Class name.class);

Ensure that the bean type is unique, or an error will be reported: org springframework. beans. factory. NoUniqueBeanDefinitionException

C is obtained by id + type

People bean = context.getBean("p1",People.class);
2.3 method of creating Bean object

bean property configuration

id: unique identifier of the current bean

Class: the fully qualified name / full path of the configuration class

Name: configure the name of the current bean, and multiple beans can be configured.

  • The first method: use the default constructor (commonly used) to directly call the parameterless null constructor in the bean object to create the object

    In spring's bean After the bean tag is configured in the XML file and the id and class attributes are set, the default structure will be automatically called to create the object. If there is no default empty structure, the object cannot be created.

    <bean id="Unique identification id" class="Fully qualified name of class"></bean>
  • The second method: create objects using the methods in the normal factory (create objects using the methods in a class and store them in the spring container)

    ServiceFactory factory = new ServiceFactory();
    <bean id="Unique identification of ordinary factory class" class="Fully qualified name of factory"></bean>
    <bean id="Objects that need to be created through the factory" factory-bean="Above bean of id" factory-method="Method name in factory"></bean>	
  • The third way: use the static method of ordinary factory to create objects

    <!--Create using static factory bean object-->
    <bean id="accountService" class="Full class name of factory class" factory-method="Static method of production object"></bean>
2.4 scope of bean object

To adjust the scope of the bean object, you need to configure the scope attribute and set whether it is single instance or multiple instances (only for the ApplicationContext interface, it is single instance by default)

scope: commonly used singleton,prototype

Singleton: singleton (default) the object is created when the configuration file is loaded.

When multiple instances of getBean are created

Request: applies to the request scope

Session: acts on the session scope

Global session: global, which acts on the distributed cluster environment. If it is not a cluster environment, it is a session

<bean id="Unique identification" class="Full class name" scope="singleton/prototype"></bean>
Default to singleton Singleton: objects are created only once during the entire program run.
prototype In multiple cases, the object is created several times after it is used several times during the running period of the program.
Multiple objects java of GC The garbage collection mechanism will automatically collect objects when it is detected that they are not used for a long time/Destroy.
2.5 life cycle of bean object

When the function is called, the object needs to be destroyed when the function is called. Objects are now managed by the spring core container. Therefore, spring should be responsible for calling these functions. We only need to tell spring who the initialization function is and who the destruction function is through configuration. The lifecycle function of the bean. You can configure two methods for testing at the same time.

Init method: the initialization method of the object

Destroy method: the method of destroying the object (the main method will not be called when testing, because it is too fast and can be destroyed manually. Call close(); Method, but at this time, the ApplicationContext object should be a subclass type and can no longer be an ApplicationContext type);

  • Singleton object:

    Birth: when the container is created, the object is born

    Alive: objects exist as long as the container is still there

    Death: the container is destroyed and the object is destroyed

The initialization method will be called, but if the destruction method uses the ApplicationContext interface type, the destruction method cannot be called. You need to use the sub interface type to see that the destruction method is called. context.close();

  • Multiple objects

    Birth: created only when objects are used

    Live: live as long as you use it

    Death: java garbage collection mechanism. When the object is not used for a long time, GC garbage collection mechanism will automatically recycle.


​ 1. Review all knowledge points

​ 2. Master the knowledge points explained today

​ 3. Preview dependency injection and spring MVC

​ 4. If you can't add, delete, change and check, go on!

Section 4: dependency injection DI

It's equivalent to inviting someone to dinner, buying clothes and giving gifts

IOC: control inversion to create objects!

Dependency injection: the purpose is to assign values to the attributes in the object.

What data types can the attributes in the object be: basic type, string, date, list <? > ---- > Basic, reference

1. Introduction

Dependency injection

The ultimate purpose of IOC control inversion is to reduce the coupling of programs, that is, to reduce dependencies.

The management of dependencies will be handed over to spring for maintenance. The management of dependencies is called dependency injection. In other words, when the current class needs to use objects of other classes, spring provides them for us. We only need to explain the maintenance of dependencies in the configuration file.

Dependency injection method:

Dependency injected data: three types

​ 1. Basic data type and String

2. other bean Entity object type(Configured in the configuration file or annotation bean)
3. Complex type/Collection type(Collection types can only be injected through configuration files)

When to create objects using IOC and DI?

For singleton objects, IOC and DI can be used. Only one object will be created during the running of the whole program, and we don't need to consider the change of data in the object.

However, if the attribute values in the object we want to create are constantly changing, DI and IOC are not recommended at this time.

2. The first method: using constructor to provide injection

​ argument

If constructor injection is used, it needs to be in the bean Add the constructor Arg tag to the bean tag of the XML file

Attributes in Tags:

Type: used to specify the type of data to be injected, which is also the type of one or some parameters in the constructor.

Index: assign a value with the parameter assigned to the specified index position in the constructor, and the index starts from 0.

Name: used to assign a value to the parameter of the constructor. Assign a value directly to the name of the specified parameter (commonly used)

value: used to provide data of basic type and String type

ref: used to specify other bean type data. It refers to beans that have appeared in spring's IOC core container

Note: when obtaining the bean object, you must inject data, otherwise the object cannot be created successfully.

Disadvantages: the instantiation method of bean object is changed. Even if we can't use this data when creating the object, we must provide it.

 <!--Structural injection-->
    <bean id="p1" class="com.bai.demo2.entity.Person">
        <constructor-arg name="age" value="18"></constructor-arg>
        <constructor-arg name="name" value="Zhang San"></constructor-arg>
        <constructor-arg name="date" ref="d1"></constructor-arg>

    <!--Date object bean-->
    <bean id="d1" class="java.util.Date"></bean>

3. The second method: injection using set method (common)

If you use the set function injection, you need to inject in the bean Add the property tag to the bean tag in the XML file

Attribute required:

name: used to assign a value to the parameter of the parameterless empty constructor and specify the set method for setting the value (remove the set of the set method and change the uppercase letter to lowercase setage() = = = > age)

value: used to provide data of basic type and String type

ref: used to specify other bean type data. It refers to beans that have appeared in spring's IOC core container

* * advantages: * * solves the problem of structural injection. You can selectively inject values instead of having to inject all.

 	<!--injection java Provided Date class-->
    <bean id="date" class="java.util.Date"></bean>
    <!--set Method injection-->
    <bean id="person" class="">
        <property name="name" value="Li Si"></property>
        <property name="age" value="29"></property>
        <property name="birthday" ref="date"></property>

3. Injection of complex data types

Array, Set (LIst, Set, Map, Properties)

<!--    to configure bean,Put on spring of IOC container-->
    <bean id="depart" class="">
        <property name="id" value="1"/>
        <property name="name" value="Tencent strategic investment research department"/>
        <!-- Injection of sets;array  n Sub tag value -->
        <property name="emps">
                <value>pony </value>
                <value>Liu Zhiping</value>
                <value>Jiang Ertao</value>
                <value>Su Lei</value>
        <property name="nicknames">
                <value>Investment Emperor</value>
                <value>Jiang Lang</value>
                <value>Su Xian</value>
        <property name="hobbies">
        <!-- How to traverse? Write first map  Entry  -->
        <property name="maps">
                <entry key="bassketball" value="Basketball"></entry>
                <entry key="pingpangball" value="Table Tennis"/>
        <!-- props:complex;Generally used in configuration files,yes Map Simplified version of;-->
        <property name="properties">
                <prop key="dirver">com.mysql.cj.jdbc.Driver</prop>
                <prop key="url">http:///school:3306</prop>
                <prop key="username">root</prop>
                <prop key="password">root</prop>

Operations on the Properties class

//If and are used to obtain the corresponding set data, after the Department is obtained; Simplified HashMap
        Properties properties = depart.getProperties();
        String driver = properties.getProperty("driver");
        String url = properties.getProperty("url");
        String username = properties.getProperty("username");
        String password = properties.getProperty("password");

5.SpEL, EL expression, output variables on the web page;

 <!--spel:Format;#{id name of bean. Attribute name} -- >
     <bean id="emp" class="">
         <property name="eid" value="2"/>
         <property name="ename" value="Qiao Yuqi"/>
         <property name="dname" value="#{}"/>

6. Inject external documents

The expression ${key} in XML represents a variable value corresponding to the key in the imported properties file, which is completely parsed by the third-party jar and read in XML format.

In order to solve many invalid configuration files, annotations can be used.

4. The third method: using annotation to provide (pay attention to opening the package scanning of annotation)

<beans xmlns=""
	<!--Enable annotation package scanning-->
    <context:component-scan base-package="Full name of the package to scan"></context:component-scan>

Annotation classification:

1. For creating objects:

The function is the same as that of writing a < bean > tag in the xml configuration file

@Component:((used as long as it does not belong to the three-tier architecture)
	Function: used to store the current class object into spring In the container.
	have value Property to specify bean of id,If you don't write value,The default corresponds to the current class name(Change initial to lowercase)
	@Component("student1")The function is equivalent to:
	<bean id="student1" class="Full class name"></bean>	
Three notes are derived:
@Controller(Presentation layer)     @Service(Business layer)      @Repository(Persistent layer)
	The role and significance of these three annotations@Component Like annotations, yes spring The framework provides us with clear annotations for the use of the three-tier architecture, which makes our three-tier architecture clearer.

2. For injecting data

The function is the same as that of the property tag in the bean tag in the xml file

@Autowired a key
 Function: automatically inject according to the type, as long as there is a unique one in the container bean If the object type matches the variable type to be injected, the injection can be successful.
    If IOC There is no in the container bean If the type of matches the type of the variable to be injected, an error is reported
    If IOC When there are multiple types matching in the container, the variable name to be injected will be used as the id To match. If it matches, it can be executed. Otherwise, an error will be reported.
Note: when using annotations, set Method is not necessary.
above@Autowired Annotation has certain limitations,(If there are multiple identical objects in the core container, only@Autowired It cannot be injected successfully)How to solve the problem?
	Function: inject by name on the basis of injecting by type. It cannot be used alone when injecting class members. But when injecting the method again, you can.
	Properties: value Used to specify the injected bean of id
	Function: directly according to bean of id Inject. It can be used independently.
	Properties: name   Used to specify bean of id
 The above three annotations can only be injected into other annotations bean Types of data, while basic types and String Type cannot use the above annotation. So how to inject basic data types and String What about the type? (collection type can only be passed through xml Injection)
	Function: used to inject basic data types and String Data type.

3. For changing the scope of action:

The function is the same as that of the scope attribute in the bean tag

	Role: used to specify bean Scope of action
	Properties: value  Specifies the value of the range. Commonly used  singleton  prototype

4. Life cycle related:

The function is the same as that of init method and destroy method in bean tag

@PostConstruct:Used to specify the initialization method
@PreDestroy	  :Used to specify the destruction method
5. Test


Differences between BeanFactory interface and ApplicationContext interface:

getBean() method

Dependency injection:

Structural injection

set injection

Annotation injection


Transformation of three-tier architecture

Simulated three-tier architecture



Controller (test class)

Clarify dependencies.

Function: inject directly according to the id of the bean. It can be used independently.
Attribute: name is used to specify the id of the bean
The above three annotations can only inject data of other bean types, while the basic type and String type cannot use the above annotations. So how to inject basic data types and String types? (collection types can only be injected through xml)
Function: used to inject basic data type and String data type.

[External chain picture transfer...(img-SEsBVE0f-1645885880932)]

**3.Used to change the scope of action**: 

​		Function and bean In label scope Property has the same function

	Role: used to specify bean Scope of action
	Properties: value  Specifies the value of the range. Commonly used  singleton  prototype

4. Life cycle related:

The function is the same as that of init method and destroy method in bean tag

@PostConstruct:Used to specify the initialization method
@PreDestroy	  :Used to specify the destruction method
5. Test


Differences between BeanFactory interface and ApplicationContext interface:

getBean() method

Dependency injection:

Structural injection

set injection

Annotation injection


Transformation of three-tier architecture

Simulated three-tier architecture



Controller (test class)

Clarify dependencies.

Use bean XML configuration, and annotation configuration. Complete the call of three-tier architecture.

Topics: Java JavaEE Spring