Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the basic contents of Spring-IOC

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "what are the basic contents of Spring-IOC". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what are the basic contents of Spring-IOC"?

Section 1 Spring IoC fundamentals

1.1 differences between BeanFactory and ApplicationContext

BeanFactory is the top-level interface of the IoC container in the Spring framework, it is only used to define some basic functions, define some basic specifications, and ApplicationContext is its small sub-interface, so ApplicationContext has all the functions provided by BeanFactory.

Usually, we call BeanFactory the basic container of SpringIOC, and ApplicationContext is the advanced interface of the container, which has more functions than BeanFactory, such as internationalization support and resource access (xml,java configuration class), and so on.

How to start the IoC container

Start IoC container in Java environment

ClassPathXmlApplicationContext: load the configuration file from the root path of the class (it is recommended to load)

FileSystemXmlApplicationContext: loading configuration files from disk path

AnnotationConfigApplicationContext: start the Spring container in annotated-only mode

Start IoC container in Web environment

Launch the container from xml

Archetype Created Web Application contextConfigLocation classpath:applicationContext.xml org.springframework.web.context.ContextLoaderListener

Start the container from the configuration class

Archetype Created Web Application contextClass org.springframework.web.context.support.AnnotationConfigWebAppli cationContext contextConfigLocation com.bxc.SpringConfig org.springframework.web.context.ContextLoaderListener

1.2 pure xml mode

In this part, we do not use the way of explaining knowledge points, but use Spring IoC pure xml mode to transform our handwritten IoC and AOP implementation, and string all knowledge points together in the process of transformation.

Xml file header

Three ways to instantiate Bean

Method 1: use a no-parameter constructor

By default, it creates an object by calling a no-parameter constructor through reflection. If there is no no-parameter constructor in the class, the creation fails.

Method 2: create using a static method

In actual development, sometimes the object we use can not be created directly through the constructor, it may do a lot of extra operations in the process of creation. At this point, a method for creating an object is provided, which happens to be a static-decorated method, as is the case. For example, when we do the Jdbc operation, we will use the implementation class of the java.sql.Connection interface. If it is a mysql database, then we will use JDBC4Connection, but we will not write

JDBC4Connection connection = new JDBC4Connection ()

Because we want to register the driver, we also provide URL and credential information, and use the DriverManager.getConnection method to obtain the connection. Then in the actual development, especially the early projects did not use the Spring framework to manage the creation of objects, but used the factory pattern decoupling in the design, then when connected to spring, the factory class created objects have the same characteristics as the above examples, and can be configured in this way.

Method 3: create using instantiation method

This approach is actually similar to the static method creation above, except that the method used to get the object is no longer static-decorated, but a normal method in the class. This approach is more likely to be used than static method creation. In early development projects, the methods in the factory class may be static or non-static, and when they are non-static, you can configure them in the following ways:

X and Life cycle of Bean

Change of scope of action

When the spring framework manages the creation of Bean objects, Bean objects are singleton by default, but it supports changing the scope in the way it is configured. The official description of the scope of action is shown in the following figure:

Of the options provided in the figure above, the most common areas of use in our actual development are singleton (singleton pattern) and prototype (prototype pattern, also known as multiple pattern). Refer to the following code for configuration:

The life cycle of different areas of action

Singleton mode: singleton

Object birth: when a container is created, the object is created.

The object is alive: as long as the container is there, the object is alive.

Object death: when the container is destroyed, the object is destroyed.

Summary: the life cycle of the bean object in the singleton pattern is the same as that of the container.

Multiple-instance mode: prototype

Object birth: when an object is used, a new object instance is created.

The object is alive: as long as the object is in use, it is still alive.

Object death: when the object is not in use for a long time, it is reclaimed by java's garbage collector.

Summary: for multiple bean objects of the schema, the spring framework is only responsible for creating, not destroying.

Bean tag attribute

In a xml-based IoC configuration, the bean tag is the most basic tag. It represents several objects in the IoC container. In other words, if each object wants to be managed by spring, you need to use this tag in the configuration of XML, as shown in the attributes of the Bean tag

Below:

Id attribute: used to provide a unique identity to bean. Within each tag, the identity must be unique.

Class property: used to specify the fully qualified class name under which the Bean object is created.

Name attribute: used to provide bean with one or more names. Multiple names are separated by spaces.

Factory-bean property: used to specify the only identity of the factory bean that created the current bean object. When this property is specified, the class property becomes invalid.

Factory-method property: used to specify the factory method for creating the current bean object. If used with the factory-bean property, the class property is invalid. If used with the class property, the method must be static.

The scope property: lets you specify the scope of the bean object. Usually it is singleton. When multiple cases mode is used, it can be configured as prototype.

Init-method property: used to specify the initialization method of the bean object, which is called after the bean object is assembled. It must be a no-parameter method.

Destory-method property: used to specify the destruction method of the bean object, which is executed before the bean object is destroyed. It works only when scope is singleton.

Xml configuration of DI dependency injection

Classify according to the way of injection

Classify by injected data type

Constructor injection: as the name implies, the parameter constructor is used to realize the data assignment to the class members.

Set method injection: it annotates the data through the set method of the class member. (the most frequently used)

Primitive types and String-injected data types are primitive types or string types.

The data type injected by other Bean types is the object type, and the reason for calling it another Bean is that this object is required to appear in the IoC container. So for the current Bean, it is other Bean.

Complex types (collection types) the data types injected are the other types in Aarry,List,Set,Map,Properties.

Dependency injection classification

The constructor injection of the configuration implementation of dependency injection, as its name implies, is to use the constructor to realize the assignment of class members. The requirement for its use is that the number of constructor parameters provided in the class must be equal to the number of configured parameters, and the data types match.

Match. At the same time, it is important to note that when there is no parameter construct, the injection of constructor parameters must be provided, otherwise the Spring framework will report an error.

When using constructor injection, the tag involved is constructor-arg, which has the following attributes:

Name: used to assign values to parameters with a specified name in the constructor.

Index: used to assign values to parameters in the constructor that specify the location of the index.

Value: data used to specify either the basic type or the String type.

Ref: data used to specify other Bean types. It is written as the only logo of other bean.

Set method injection for configuration implementation of dependency injection

As the name implies, it uses the set method of the field to achieve the injection of the assignment. This method is the most frequently used injection method in actual development.

When using the set method injection, you need to use the property tag, which has the following attributes:

Name: specifies the name of the set method that is called during injection. (note: does not include the letters set, druid connection pool specifies the attribute name)

Value: specifies the injected data. It supports basic types and String types.

Ref: specifies the injected data. It supports other bean types. It is written as the only logo of other bean.

Complex data type injection first of all, explain the complex type data under the collection, which refers to the collection type data. The collection is divided into two categories, the List structure (array structure) and the Map interface (key-value pair).

The next step is to choose the way to inject, which can only be selected between the constructor and the set method. Our example uses the set method injection.

When the collection data of List structure is injected, the three tags array, list and set are common. In addition, the value can be written directly inside the value tag of the value, or you can use the bean tag to configure bean objects, or use the ref tag to refer to the unique identity of a matched bean.

When annotating the collection data of the Map structure, the map tag uses the entry child tag for data injection, and the entry tag can use the key and value attributes to specify the data in the storage map. Use the value-ref property to specify a reference to the configured bean. You can also use the ref tag in the entry tag, but not the bean tag. Ref or bean tags cannot be used to reference objects in property tags

1.3 combination of xml and annotations

Note:

1) in actual enterprise development, pure xml mode is seldom used.

2) introduce annotation function, no need to introduce additional jar

3) in the xml+ annotation combination mode, the xml file still exists, so the startup of the spring IOC container still starts from loading xml

4) which bean definitions are written in xml and which bean definitions are annotated

Bean in third-party jar is defined in xml, such as druid database connection pool

Self-developed bean definitions using annotations

Correspondence between tags and comments in xml (IoC)

Annotation implementation of DI dependency injection

@ Autowired (recommended)

@ Autowired provides annotations for Spring, and you need to import the package org.springframework.beans.factory.annotation.Autowired.

The strategy adopted by @ Autowired is to inject by type.

Public class TransferServiceImpl {@ Autowired private AccountDao accountDao;}

As shown in the code above, this assembly goes back to the spring container to find the class of type AccountDao, and then inject it. This will give rise to a problem. When a type has more than one bean value, it will make it impossible to choose which one to note.

At this point we need to use it with @ Qualifier. Qualifier tells Spring exactly which object to assemble.

Public class TransferServiceImpl {@ Autowired @ Qualifier (name= "jdbcAccountDaoImpl") private AccountDao accountDao;}

At this point, we can locate the object we want to inject by type and name.

@ Resource

The @ Resource annotation is provided by J2EE, and the guide package javax.annotation.Resource is required.

@ Resource is automatically injected according to ByName by default.

Public class TransferService {@ Resource private AccountDao accountDao; @ Resource (name= "studentDao") private StudentDao studentDao; @ Resource (type= "TeacherDao") private TeacherDao teacherDao; @ Resource (name= "manDao", type= "ManDao") private ManDao manDao;}

If both name and type are specified, a matching bean is found in the Spring context to assemble, and an exception is thrown if it is not found.

If name is specified, a bean with a matching name (id) is found in the context for assembly, and an exception is thrown if it is not found.

If type is specified, a similar matching only bean is found in the context for assembly, and an exception is thrown if no or more than one is found.

If neither name nor type is specified, the assembly will be carried out in byName mode automatically

Note:

@ Resource has been removed in Jdk 11. If you want to use it, you need to introduce the jar package separately.

Javax.annotation javax.annotation-api 1.3.2 1.4 annotated mode only

Transform the xml+ annotation mode, migrate all the remaining content in xml in the form of annotations, and finally delete xml and start from the Java configuration class

Corresponding annotations

@ Configuration annotation, table name the current class is a configuration class

@ ComponentScan annotation, instead of context:component-scan

@ PropertySource, quote the external properties profile

@ Import introduces other configuration classes

@ Value assigns values to variables, either directly or by using ${} to read the information in the resource configuration file

@ Bean returns the method to the object plus the SpringIOC container

Thank you for your reading, these are the contents of "what are the basic contents of Spring-IOC". After the study of this article, I believe you have a deeper understanding of what is the basic content of Spring-IOC, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report