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 is the design concept of IOC container and how to write the source code?

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

What is the concept of IOC container design and how to write the source code, I believe that many inexperienced people are at a loss about this. Therefore, this article summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

A Review of the Theory of IOC and Nucleus

Knowledge points:

1. Summary of Ioc concept

two。 Creation of entity Bean

3. Basic characteristics of Bean

4. Dependency note

1. Summary of Ioc theory.

In the world of JAVA, how can object A tune object B? There are usually the following "methods".

Category description time step

External transmission

When you construct a Dharma pass and create a reference object

When you set the state of an object by setting the property

When the operation is used as a parameter, when it is transmitted and adjusted.

Internal creation

When you create a reference object directly in the

When initializing a guide method to create a reference object

When you dynamically create a call during the operation

As can be seen in the above table, the target can be completed by different methods in different places (other introducers) and at different times.

Yes. If B is just a simple object such as direct new B (), it will never feel complicated, such as you will never

I feel that creating a St ring is a complicated thing. But if B is a Service object with complex dependencies, this

Introducing B at different times will become very complicated.

It is necessary to maintain the complex dependency relationship of B all the time. Imagine that if there are more than a hundred items in the B object, the system complexity will accompany it.

The number increased.

The emergence of IOC container is to solve this problem. It can integrate the construction of objects and maintain the dependence of objects.

Depend on the relationship to reduce the implementation cost of the system. The premise is that you need to declare the target object based on XML in advance.

2. The construction of entity Bean

a. Build based on Class

b. Construction by the method of construction

c. Creation of static flooding method

D. Fact oryBean creation

1. Build based on ClassName

This is the most conventional alternative, and the principle is that at the bottom of the spring, it is built by reflecting into class based on the class attribute.

2. Construction by the method of construction.

If you need to build based on parameters, use the "construction" method to build it. The corresponding attributes are as follows:

Name: constructor parameter variable name

T ype: parameter type

Index: parameter index, starting with 0

Value: parameter value. Spring will convert the parameter to the actual type value.

Ref: other objects that refer to the capacity string

3. Create static flooding method.

one

two

three

four

one

two

three

If you are testing a number of objects, you can use the static creation method, which is based on the strategy.

Create different objects or populate different attributes.

In this mode, a static method must be created, and the method returns the instance, and spring will adjust the static method.

Create an object.

4. Fact oryBean creation

Specify "Bean administrators" to create objects, and the initialization of object construction is entirely left to the administrators to implement. Specify this when configuring Bean

The class name of the categories class.

3. Basic characteristics of bean

? Scope of operation

Life cycle

? Loading mechanism

Public static HelloSpring build (1 String type) {

2 if (type.equals ("A")) {

3 return new HelloSpring ("luban", "man")

4} else if (type.equals ("B")) {

5 return new HelloSpring ("diaocan", "woman")

6} else {

7 throw new IllegalArgumentException ("type must An or B")

8}

9}

one

two

three

1 public class DriverFactoryBean implements FactoryBean {

2 private String jdbcUrl

3 public Object getObject () throws Exception {

4 return DriverManager.getDriver (jdbcUrl)

5}

6 public Class getObjectType () {

7 return Driver.class

8}

9 public boolean isSingleton () {

10 return true

11}

12 public String getJdbcUrl () {

13 return jdbcUrl

14}

15 public void setJdbcUrl (String jdbcUrl) {

16 this.jdbcUrl = jdbcUrl

17}

18}

A, the scope of operation

Most of the time, Bean objects are stateful, and some of them are stateful. For objects with stateful state, we can take a singleton.

The state must be a multi-instance mode, which can be created through scope

Scope= "prot ot ype"

Scope= "singlet on"

If the Bean is set to prot ot ype, we can get the BeanFact ory object through BeanFact oryAware

That is, every time you get a new target.

B. Life cycle

The creation, initialization and destruction of Bean objects are the lifetime of Bean. Through init-met hod, dest roymet

The hod attribute can refer to periodic construction methods and initialization methods, respectively.

If you find it troublesome, you can ask Bean to implement Init ializingBean.af t erPropert iesSet (),

DisposableBean.dest roy () method. Corresponding to initial and destruction methods, respectively.

C, loading mechanism

Indicates when the Bean is loaded. You can set lazy-init. The values are as follows:

T rue: lazy loading, that is, delayed loading

F alse: lazy loading, creating objects when the container starts

Def ault: the value specified in def ault-lazy-init is selected by default. If def ault-lazy-init is not specified, it is.

F alse

When will the lazy load be made?

Lazy loading will make the container start faster, lazy loading can find errors in the program faster when the container starts, which one to choose?

It depends on whether we pursue the start-up speed or hope to find the error earlier, so we will choose the latter.

4. Dependency notes

Imagine that if there are no dependency notes in IOC, then this framework can only help us build "some simple Bean," as mentioned before.

The problem of building a complex Bean will be solved, and the framework of spring will not be as successful as it is now. In spring

How does ioc rely on annotations? There are the following "types":

1. Set remarks

two。 Note on the structural method

3. "byName, byT ype"

4. Lookup-met hod

1. Set remarks

1 scope= "prototype

two

three

one

one

2. Notes on structural methods.

3. "byName\ byT ype\ const ruct or"

ByName: insert based on the same variable name as bean name

ByT ype: based on variable category and bean name

Const ruct or: based on the matching of bean and construction "normal advance" in IOC (semantic ambiguity, not recommended)

4. Rely on lookup-met hod.

When a single case of Bean depends on several cases of Bean, the "conventional" method will only be annotated several times, if each time

If you want to get a brand new instance, you can use the "lookup-met hod" method to achieve it.

The principle of this operation is based on the dynamic proxy technology, re-create an inherited standard class, and then rewrite the abstract method to the note.

Yes, it is.

The case in which the single Bean depends on multiple Bean can also be realized by implementing Applicat ionCont ext Aware,

BeanFact oryAware receives the BeanFact ory instance, and obtains the new reality from the method of "you can directly adjust the get Bean".

For example, it is recommended to make the semantic logic of this method and relative lookup-met hod clearer.

The design principle and implementation of IOC.

two

three

one

two

three

four

five

one

two

1 # write an abstract class

2 public abstract class MethodInject {

3 public void handlerRequest () {

4 / / get the latest instance by calling the abstract method

5 getFine ()

6}

7 # write an abstract method

8 public abstract FineSpring getFine ()

9}

10 / / implementation of setting abstraction method

eleven

twelve

thirteen

Knowledge points:

1. The standard of source code learning

2. The construction process of Bean.

3. The difference between BeanFact ory and Applicat ionCont ext

1. Source code learning standard:

Don't read in order to read, nor read the source code in order to read the source code. The head without a horse plunges into the forest of source code.

I soon got lost. At that time, we will not read the source code, but we will be poisoned by the source code. After all, the framework is made up of professional groups.

Team, the product of N version iterations, we can't expect to read it like we read this book. So you have to read the source code.

I found the sign before. What is it?

The family will think, isn't the purpose of reading the source code logo to learn? This kind of labeling is too abstract, which is verified by the "labeling" method. Usually I

We will set two types of standards: one is to improve the source code, and the other is to add and modify some functions to achieve this kind of standard.

Cheng Zhongran will gradually become familiar with and understand the item. But this is more difficult, and the cost is also low. Another way to do this is

Please ask some questions, and reading the source code is to find answers to these questions. Here's what we need to get up and look for answers in the source code.

The question of the case:

1. How do Bean manufacturers produce Bean?

2. Who decides the dependency of Bean?

3. What is the difference between Bean service and response service?

2. The construction process of Bean.

Our description configuration for Bean is saved in the spring.xml installer, and BeanFact ory reads these configurations and then reads

Corresponding Bean. This is our general understanding of the principle of ioc. But will we have more questions in the deep aisle?

1. Who is the last JAVA and which object hosts the configuration information?

two。 Who reads and loads these bearer objects from XML?

3. Where are these bearer objects saved?

BeanDefinit ion (Bean definition)

The Bean information we described in xml in the ioc implementation will eventually be saved in the definition BeanDefinit ion object.

The relationship between xml bean and BeanDefinit ion.

As a result, the properties set in xml bean will eventually be reflected in BeanDefinit ion. Such as:

Show me how to view BeanDefinit ion property structure

BeanDefinit ionRegist ry (Bean registrar)

In the above table, we do not see that the id and name attributes in xml bean are not reflected in the definition because ID does

Registered with the BeanDefinit ionRegist ry registry for the storage key of the current Bean. Name is registered as alias key

To the AliasRegist ry registration center. In the end, they all point to their corresponding BeanDefinit ion.

Show me how to view BeanDefinit ionRegist ry property structure

XML-bean BeanDefinit ion

Class beanClassName

Scope scope

Lazy-init lazyInit

Const ruct or-arg Const ruct orArgument

Propert y MutablePropertyValues

F actory-met hod f actoryMethodName

Dest roy-met hod Abst ract BeanDefinit ion.dest royMet hodName

Init-met hod Abst ract BeanDefinit ion.init Met hodName

Aut owire Abst ract BeanDefinit ion.aut owireMode

Id

Name

?

?

BeanDefinit ionReader (Bean definition read)

"We learned that Xml Bean information is stored in BeanDefinit ion," BeanDefinit ionRegist er is based on ID.

And name save the definition of Bean. The next thing to learn is to go from xml Bean to BeanDefinit ion and then register

BeanDefinit ionRegist er the whole process.

As you can see in the figure above, the definition of Bean is that BeanDefinit ionReader reads the configuration from the xml and builds the

BeanDefinit ionReader, and then register with BeanDefinit ionRegist er based on the alias.

Check BeanDefinit? IonReader structure

Description of the law:

? LoadBeanDefinit ions (Resource resource)

? Load the Bean definition and register the registry based on resources

? Int loadBeanDefinit ions (St ring locat ion)

? Load the Bean definition and register the register based on the resource path

? BeanDefinit ionRegist ry get Regist ry ()

? Get the registrar

? ResourceLoader get ResourceLoader ()

? Get resource loader

Demonstrate the BeanDefinit ionReader loading process based on examples

Beanf act ory (bean subscription)

Having the definition of Bean is equivalent to having the matching of the product, and the next step is to send the product to the factory for production.

In ioc, BeanFact ory is responsible for the construction of Bean. Its structure is as follows:

?

1 / / create a simple registrar

2 BeanDefinitionRegistry register = new SimpleBeanDefinitionRegistry ()

3 / / create a bean definition reader

4 BeanDefinitionReader reader = new XmlBeanDefinitionReader (register)

5 / / create a resource reader

6 DefaultResourceLoader resourceLoader = new DefaultResourceLoader ()

7 / / get resources

8 Resource xmlResource = resourceLoader.getResource ("spring.xml")

9 / / load the definition of Bean

10 reader.loadBeanDefinitions (xmlResource)

11 / / print the Bean name of the build

12 System.out.println (Arrays.toString (register.getBeanDefinitionNames ()

Description of the law:

? Get Bean (St ring)

? Get two Bean based on ID or name

? T get Bean (Class requiredT ype)

? Get a Bean based on the category of Bean (if there are multiple instances of this class, an error will be reported. But you can specify

Primary= "t rue" adjusts priority to resolve this error)

? Object get Bean (St ring name, Object... Args)

? Gets a Bean based on the name and overrides the default construction parameters

? Boolean isT ypeMat ch (St ring name, Class t ypeT oMat ch)

? Specifies whether the Bean matches the specified Class

`

In the above method, we should focus on get Bean. When a customer calls get Bean, the creation action of Bean will be triggered, and its

How was it created?

Demo key? This BeanFactory gets a Bean.

1 # create Bean stack

2 / / its reflection instantiates Bean

3 java.lang.reflect.Constructor.newInstance (Unknown Source:-1)

4 BeanUtils.instantiateClass ()

5 / / instantiate Bean based on instantiation policy

6 SimpleInstantiationStrategy.instantiate ()

7 AbstractAutowireCapableBeanFactory.instantiateBean ()

8 / / instantiation method of executing Bean

9 AbstractAutowireCapableBeanFactory.createBeanInstance ()

10 AbstractAutowireCapableBeanFactory.doCreateBean ()

11 / / execute the creation of Bean

12 AbstractAutowireCapableBeanFactory.createBean ()

13 / / not in the cache. Call the specified Bean factory to create Bean

14 AbstractBeanFactory$1.getObject ()

15 / / obtain Bean cache from singleton registry

16 DefaultSingletonBeanRegistry.getSingleton ()

17 AbstractBeanFactory.doGetBean ()

Bean creation sequence diagram:

The following points can be summarized from the tuning process:

1. Calling BeanFact ory.get Bean () triggers the instantiation of Bean.

2. A single Bean is cached in Def ault Singlet onBeanRegist ry

3. The creation and initialization of Bean is completed by Abst ract Aut owireCapableBeanFact ory.

3. The difference between BeanFactory and ApplicationContext

BeanFact ory seems to be able to do some of the things in IOC, so why define it?

Where's Applicat ionCont ext?

Applicat ionCont ext structure diagram

You can see from the picture that Applicat ionCont ext is sent by BeanFact ory because it provides

All the functions of BeanFact ory. In addition, the cont ext package provides the following features:

1. MessageSource, which provides international message access

two。 Resource access, such as URL and components

3. Event propagation, which implements the bean of Applicat ionList ener connection

4. Load "multiple (inheriting) up and down", so that each "up and down" focuses on "a specific level, such as should be"

Web layer of

Summary and review:

BeanDefinit ion

Def ault ResourceLoader

XmlBeanDefinit ionReader

BeanDefinit ionRegist ry

18 / / get Bean

19 AbstractBeanFactory.getBean ()

20 / / the client class called

21 com.tuling.spring.BeanFactoryExample.main ()

BeanFact ory

Def ault List ableBeanFact ory

Aut owireCapableBeanFact ory

Abst ract Aut owireCapableBeanFact ory

Singlet onBeanRegist ry

Def ault Singlet onBeanRegist ry

After reading the above, have you mastered the concept of IOC container design and how to write the source code? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

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

Internet Technology

Wechat

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

12
Report