Spring IOC knowledge point clean sweep!

Source: Internet
Author: User
Tags aop reflection

Objective

Only a bald head can become stronger.

Review Front:

    • Explain to your girlfriend what proxy mode is.
    • The packing pattern is so simple.
    • How many ways do you make a single pattern?
    • Does the factory model understand?

It took a while to brush the spring books to learn about the singleton mode and the factory model, and it was worth it in general!

Originally wanted to brush the "Spring Combat (4th edition)" and "Proficient in spring4.x enterprise application Development Practice" of the IOC chapter later to re-write an IOC article, read the beginning of the previous series of the introduction of spring this article is enough and spring "dependency injection" It's that simple. The most important point of knowledge has already been told, so feel there is no need to re-write these points of knowledge ...

I personally do not like to write the things copied to the new article, so it is recommended that you can read the above two articles and then look at this (Factory mode that if you have not seen the students also need to see) ~ ~

    • For the completeness of the knowledge points in this article, the important points of knowledge (IOC concept understanding, the creation of beans, injection of three ways, etc.) will still appear, but will not be the code of the above two post excerpt.

This article is mainly to complement and strengthen some of the more important points of knowledge, and will be the above two books on the IOC Knowledge points and draw a mind map to fully understand the spring IOC knowledge points!

So let's get started, if there's something wrong, and you want to forgive, and don't hesitate to comment!

I. Comprehensive understanding of Spring IOC

Combining the "Spring Combat (4th Edition)" and "Proficient in spring4.x enterprise application development" two books of the IOC chapter to organize their knowledge points ~

1.1IOC and Di overview

In the "Proficient spring4.x enterprise Application Development Practice" in the definition of IOC is this:

The IoC (inversion of control) controls inversion, contains two aspects: first, control. Second, reverse

We can simply say:

    • Control refers to the current object's control over internal members .
    • Inversion means that this control is not managed by the current object and is managed by other (classes, third-party containers).

The IOC was not straightforward enough, and Martin Fowler proposed Di (dependency injection) to replace the IOC, where the invocation class's dependency on an interface implementation class was injected by a third party (container or collaboration Class) to remove the invocation class's dependency on an interface implementation class.

In Spring Combat (4th Edition), the IOC is not mentioned, but directly to Di:

With Di, the object's dependencies are set by the system's third-party components that coordinate the objects, and the objects do not have to create or manage their own dependencies, and the dependencies are automatically injected into the objects that need them.

From the book we can also find that the definition of the IOC and DI (the difference) is not so easy to say clearly. Here I will briefly excerpt :

    • There are two main ways to implement the IoC (thought, design pattern): Dependency lookup, Dependency Injection .
    • Dependency injection is a more desirable approach (the way it is implemented)

For us, there is no need to be so clear, mixing a talk does not affect our understanding ...

Did you understand it by the factory model I wrote yesterday? , we can now clearly find that the so-called IOC container is a big factory "third-party container" (Spring implementation of the function is very powerful!) Much better than our own hand-written factory).

The benefits of using IOC (@intopass's answer):

    1. You don't have to assemble them, you use them.
    2. Enjoy the benefits of a single case, high efficiency, without wasting space.
    3. Easy unit testing for easy switching of mock components.
    4. Facilitates AOP operations and is transparent to the consumer.
    5. Unified configuration for easy modification.

Resources:

    • What are the benefits of the https://www.zhihu.com/question/23277575--Spring IOC?
Principle of the 1.2IOC container

It has been said from the above: the IOC container is actually a big factory that manages all of our objects and dependencies.

    • The principle is through the Java Reflection technology to achieve! By reflection we can get all the information of the class (member variables, class names, etc.)!
    • describe the relationship between classes and class through configuration files (XML) or annotations
    • We can use these configuration information and reflection technology to build the corresponding object and dependency relationship!

As long as the technology described above can be spoken by a little bit of Java, this can suddenly be questioned by the interviewer, so let's simply look at how the actual spring IOC container implements the object creation and dependency:

    1. Create a Bean definition registry from within a container based on bean configuration information
    2. Load, instantiate, and establish a dependency between beans and beans based on the registry
    3. Put the ready beans in the map cache pool, waiting for the application to call

The spring container (bean Factory) can be easily divided into two types:

    • Beanfactory
      • This is the most basic, spring-oriented
    • ApplicationContext
      • This is based on beanfactory, for developers using the spring framework. offers a range of features!

applicationcontext! is used in almost all applications

Beanfactory's Inheritance system:

ApplicationContext's Inheritance system:

Among the ApplicationContext subclasses, there is one more important: Webapplicationcontext

    • Specially prepared for Web applications

Web applications and Spring convergence:

Let's look at the life cycle of beanfactory:

Then let's look at the life cycle of ApplicationContext:

The initialization process is long and we can classify it to parse it:

    • The Bean's own method : Call the Bean constructor to instantiate the bean, call the Setter to set the Bean's property value, and
    • bean-level life-cycle interface methods such as Beannameaware, Beanfactoryaware, Initializingbean, and Disposablebean, which are implemented directly by the Bean class;
    • container-Level Lifecycle interface method : The Step with "★" is implemented by the two interfaces of Instantiationawarebean Postprocessor and Beanpostprocessor, which is generally called the implementation class " After the processor . The post-processor interface is generally not implemented by the bean itself, which is independent of the bean, the implementation class is registered in the container attachment to the spring container and is reflected by the interface to the spring container pre-identified. When the spring container creates any beans, these post-processors all work, so the impact of these post-processors is global. Of course, the user can simply write the post processor so that it is only processed for the bean of interest

the difference between ApplicationContext and Beanfactory is that:

    • ApplicationContext uses the Java reflection mechanism to automatically identify the beanpostprocessor, Instantiationawarebeanpostprocesso defined in the configuration file. and Beanfactorypostprocessor , and automatically registers them in the application context. and beanfactory needs to be registered in code by calling the method manually. addBeanPostProcessor()
    • ApplicationContext instantiates all single-instance beanswhen the application context is initialized . Beanfactory does not instantiate the bean when it initializes the container, and then instantiates the target bean until it accesses a bean for the first time.

With the above knowledge point, let's look at the bean initialization process in detail :

Brief summary:

    • Beandefinitionreader reads the profile resource that the resource points to, and then resolves the configuration file. Each of the configuration files <bean> is parsed into a Beandefinition object and saved to the beandefinitionregistry;
    • The container scans the beandefinition in the Beandefinitionregistry; invokes the Instantiationstrategy for the bean instantiation ; Beanwrapper to complete the setting of bean properties ;
    • Singleton bean Cache Pool: Spring provides a buffer for the instance bean of the Defaultsingletonbeanregistry class, which is a cache implemented with HashMap, a single-instance bean Save in this hashmap with Beanname as the key .
1.3IOC Container assembly Bean1.3.1 Assembly Bean mode

spring4.x start an IOC container assembly Bean in 4 ways:

    • XML configuration
    • Annotations
    • Javaconfig
    • Based on Groovy DSL configuration (this is rarely seen)

In general: We assemble more beans with XML config + annotations, in which the annotations are most of the way!

1.3.2 Dependency Injection method

There are 3 ways to rely on injection:

    • attribute Injection ---through setter() method injection
    • Constructor injection
    • Factory Method Injection

In general, the use of attribute injection is more flexible and convenient, this is the choice of most people!

1.3.3 Relationships between objects

<bean>There are three types of relationships between objects:

    • Dependent--Very little (using Depends-on is the dependency----the current bean is initialized after the dependency-dependent bean needs to be initialized)
    • Inheritance-may be used (specify abstract and parent to implement inheritance relationships)
    • Reference--the most common (using ref is a reference relationship)
Scope of 1.3.4Bean

Scope of the Bean:

    • Single Case Singleton
    • Multiple cases of prototype
    • Bean scopes related to the Web application environment
      • Reqeust
      • Session

Using the bean scope related to the Web application environment, we need to manually configure the agent 's ~

The reason is also simple: because our default bean is Singleton, in order to fit the bean scope related to the Web application environment---> Each request requires an object, we return a proxy object to go out to complete our needs!

There is one more issue when configuring a Bean for a singleton:

    • If our bean is configured with a singleton, and the member object inside the Bean object We want is more than one example . What about that??
    • By default our Bean singleton, the returned member object also defaults to singleton (because the object is only one)!

At this point we need to use the lookup method of injection, it is very simple, to see the example is clear:

Ambiguity of automatic assembly processing in 1.3.6

When I was brushing the book yesterday, I just saw someone asking me to answer this question:

Combining the knowledge points of the two books can be summed up into two solutions:

    • Use @Primary annotations to set the preferred injection bean
    • Use @Qualifier annotations to set specific names of beans to qualify injections!
      • You can also use a custom annotation to identify
1.3.7 referencing property files and Bean properties

Before the configuration file is written directly to our database configuration information in the inside of the dead:

In fact, we have a more elegant approach : Write these configuration information to the configuration file (because these configuration information is likely to be variable and may be referenced by multiple profiles).

    • In this way, we are very convenient when we change .

The data referencing the configuration file is using the${}

In addition to referencing the data on the configuration file, we can also refer to the Bean's properties :

The properties of the reference bean are using the#{}

This technique is called Spring EL in the Spring combat fourth version, similar to the El expression we learned before. The main function is the one above, for more in-depth reference to the following links:

    • Http://www.cnblogs.com/leiOOlei/p/3543222.html
1.3.8 Combination configuration file

XML file combinations:

The way XML and Javaconfig are combined:

     Public Static void Main(string[] args) {//1. Loading a configuration class from a constructor functionApplicationContext CTX =New Annotationconfigapplicationcontext(appconf.class);//2. Registering a configuration class by encodingAnnotationconfigapplicationcontext CTX =New Annotationconfigapplicationcontext(); CTx.Register(Daoconfig.class); CTx.Register(ServiceConfig.class); CTx.Refresh();//3. Configuring the configuration information provided by the @configuration configuration class through XML assemblyApplicationContext CTX =New Classpathxmlapplicationcontext("Com/smart/conf/beans2.xml");//4. Configuring the configuration information provided by the @configuration assembly XML configurationApplicationContext CTX =New Annotationconfigapplicationcontext(Logonappconfig.class);//[email protected] 's configuration class referencing each otherApplicationContext CTX =New Annotationconfigapplicationcontext(Daoconfig.class, ServiceConfig.class); Logonservice Logonservice = ctx.Getbean(Logonservice.class); System. out.println(Logonservice.Getlogdao() !=NULL)); Logonservice.Printhelllo(); }

Examples of the first kind:

The second example:

An example of the third kind:

Example of the fourth type:

Example of the fifth type:

    • The code is visible from the
1.3.9 Assembly Bean Summary

In general, the Spring IOC container is a lot of ways to implement the bean when it is created, including a lot of configuration about the bean.

For bean-related injection tutorial code and simplified configuration (P and C namespaces) I don't have to say it all, you see the spring introduction This is enough, and spring "dependency injection" is just as simple as that.

Total Comparison chart:


Separate application scenarios:

As for some small points of knowledge:

    • Method substitution
      • Method of replacing a bean with another bean
    • Property Editor
      • Spring can convert basic types due to the property editor's credit!
    • Internationalization
      • Use operating systems in different languages (English, Chinese) to explicitly different languages
    • Profile and conditionally-typed beans
      • A condition is satisfied to initialize the bean, which makes it easy to switch between production and development environments ~
    • Container Events
      • The listener is similar to our servlet, except that it is implemented in spring ~

The above small knowledge points will be used less, this also do not explain. Know there is such a thing, then check will be used ~ ~ ~

Second, Spring IOC related questions

It is important to know which knowledge points are springioc by collating the relevant knowledge points. Very simple, we go to find the relevant interview questions to know, if the interview is common, then it is relatively important to explain this knowledge point!

The following questions from a variety of blog excerpts from the paper, a larger amount will indicate the source of ~

2.1 What is Spring?

What is Spring?

Spring is an open-source development framework for Java Enterprise applications. Spring is primarily used to develop Java applications, but some extensions are for Web applications that build the EE platform. The Spring framework goal is to simplify Java enterprise application development and promote good programming habits through the Pojo-based programming model.

2.2 What are the benefits of using the spring framework?

What are the benefits of using the spring framework?

    • Lightweight : Spring is lightweight, with a basic version of about 2MB.
    • control inversion : Spring is loosely coupled through control inversion, and objects are given their dependencies rather than creating or locating dependent objects.
    • tangent-oriented programming (AOP): Spring supports tangent-oriented programming and separates application business logic from system services.
    • containers : Spring contains and manages the life cycle and configuration of objects in your app.
    • MVC Framework : Spring's web Framework is a well-designed framework and a good alternative to web frameworks.
    • Transaction Management : Spring provides a continuous transaction management interface that can be extended up to the local transaction down to the global transaction (JTA).
    • exception Handling : Spring provides a convenient API for translating specific technology-related exceptions (such as those thrown by jdbc,hibernate or JDO) into a consistent unchecked exception.
What modules do 2.3Spring consist of?

What modules does spring consist of?

Simple can be divided into 6 large modules:

    • Core
    • Aop
    • Orm
    • DAO
    • Web
    • Spring EE

2.4BeanFactory implementation Examples

Beanfactory implementation Examples

The Bean Factory is an implementation of the factory pattern and provides a control reversal function that separates the application's configuration and dependencies from the true application code .

Most commonly used before spring3.2 is xmlbeanfactory, but is now abandoned and replaced by: Xmlbeandefinitionreader and Defaultlistablebeanfactory

2.5 What is spring's dependency injection?

What is spring's dependency injection?

Dependency injection, an aspect of the IOC, is a common concept, and it has many interpretations. The idea is that you don't have to create an object, you just need to describe how it was created. You do not assemble your components and services directly in the code, but the configuration file describes which components require which services , and then a container (the IOC container) is responsible for assembling them.

What are the different types of IOC (dependency injection) methods in 2.6?

What are the different types of IOC (dependency injection) methods?

    • constructor Dependency Injection: constructor Dependency injection is implemented by a constructor that triggers a class by the container, which has a series of parameters, each representing a dependency on another class.
    • Setter Method Injection : Setter method Injection is the method by which the container invokes the setter of the bean by invoking the parameterless constructor or the non-parametric static factory method to instantiate the bean, which implements the setter-based dependency injection.
    • Factory injection: This is a legacy, seldom used!
2.7 Which dependency injection method do you recommend using, constructor injection, or setter method injection?

Which dependency injection method do you recommend using, constructor injection, or setter method injection?

Both of your dependencies can be used, constructor injection and setter method injection. The best solution is to implement a forced dependency with constructor parameters, and the setter method implements an optional dependency .

2.8 What is spring beans?

What is spring beans?

Spring beans are Java objects that form the backbone of spring applications . They are initialized, assembled, and managed by the spring IOC container. These beans are created through the metadata that is configured in the container. For example, it is defined as a form in an XML file <bean/> .

Here are four important ways to provide configuration metadata to the spring container.

    • XML configuration file.
    • Annotation-based configuration.
    • Java-based configuration.
    • Groovy DSL Configuration
2.9 Explaining the Bean's life cycle in the spring framework

Explain the bean's life cycle in the spring framework

    • The spring container reads the bean definition from the XML file and instantiates the bean.
    • Spring populates all properties based on the Bean's definition.
    • If the bean implements the Beannameaware interface, Spring passes the Bean's ID to the Setbeanname method.
    • If the bean implements the Beanfactoryaware interface, spring passes beanfactory to the Setbeanfactory method.
    • If any beanpostprocessors,spring associated with the bean are called within the Postprocesserbeforeinitialization () method.
    • If the bean implementation is Intializingbean, call its Afterpropertyset method, and if the bean declares the initialization method, call this initialization method.
    • If there are beanpostprocessors and bean associations, the Postprocessafterinitialization () method of these beans will be called.
    • If the bean implements Disposablebean, it will call the Destroy () method.
2.10 explaining automatic assembly in different ways

Explain automatic assembly in different ways

    • No: The default way is not to assemble automatically, but by explicitly setting the Ref property.
    • ByName: Automatically assembled by the parameter name, the spring container discovers that the bean's Autowire property is set to ByName in the configuration file, and then the container tries to match, assemble, and bean whose attributes have the same name.
    • Bytype:: With automatic assembly of parameter types, the spring container discovers that the bean's Autowire property is set to Bytype in the configuration file, after which the container tries to match, assemble, and have the same type of bean as the bean's property. If more than one bean meets the criteria, an error is thrown.
    • Constructor: This is similar to Bytype, but to give the constructor arguments, an exception will be thrown if there is no deterministic constructor parameter type for the parameter.
    • AutoDetect: First try to use constructor to move the assembly, if not, use the Bytype method.

annotations are used by default when using annotations only Bytype!

What are the advantages of 2.11IOC?

What are the advantages of IOC?

IOC or dependency injection minimizes the amount of code applied. It makes the application easy to test, and unit tests no longer require singleton and Jndi lookup mechanisms. The minimum cost and minimal intrusion allow loose coupling to be achieved . The IOC container supports a hungry man initialization and lazy loading when the service is loaded.

2.12 What are the important bean life-cycle methods? Can you reload them?

What are the important bean life-cycle methods? Can you reload them?

There are two important bean life-cycle methods, the first of which is setup called when the container loads the bean. The second method is that teardown it is called when the container unloads the class.

The bean tag has two important attributes ( init-method and destroy-method ). With them you can customize the initialization and logoff methods yourself. They also have corresponding annotations ( @PostConstruct and @PreDestroy ).

2.13 How to answer the interviewer: What is your understanding of spring?

How do you answer the interviewer: Your understanding of spring?

Source:

    • https://www.zhihu.com/question/48427693?sort=created

I'll cut a few answers below:

One

Two

is the singleton beans in the 2.14Spring framework thread-safe?

is the singleton beans in the Spring framework thread-safe?

The spring framework does not have any multithreaded encapsulation of singleton beans. Thread safety and concurrency issues for singleton beans need to be done by developers themselves. In fact, most spring beans do not have a mutable state (such as the Serview class and the DAO Class), so spring's singleton beans are, to some extent, thread-safe. If your bean has multiple states (such as the View Model object), you will need to ensure thread safety yourself .

The most obvious solution is to change the scope of the polymorphic bean from "Singleton" to "prototype"

What is the difference between 2.15FileSystemResource and Classpathresource?

What is the difference between Filesystemresource and Classpathresource?

In Filesystemresource, you need to give the relative path or absolute path of the Spring-config.xml file in your project. In Classpathresource spring will automatically search for the configuration file in Classpath, so put the Classpathresource file under Classpath.

If you save spring-config.xml in the src folder, just give the name of the configuration file, because the SRC folder is the default.

In short, Classpathresource reads the configuration file in theenvironment variable and Filesystemresource reads the configuration file in the configuration file.

Iii. Summary

The main point of this article I drew a mind map summary, when learning to AOP, this mind mapping will continue to add Oh ~ ~ ~

Resources:

    • "Spring Combat"
    • Proficient in the application development of spring4.x Enterprise
    • Https://zhuanlan.zhihu.com/p/29344811--Spring IOC Principle Summary
    • 52453002---java face question set (vii)--spring Common interview questions
    • https://zhuanlan.zhihu.com/p/31527327--69 A classic Spring noodle question and answer

If the article is wrong, welcome to correct, we communicate with each other. Accustomed to looking at technical articles, want to get more Java resources of students, can pay attention to the public number: Java3y. For everyone's convenience, just new QQ Group: 742919422, we can also go to exchange. Thanks for the support! I hope to introduce more to other needy friends.

Directory navigation for articles :

    • Https://zhongfucheng.bitcron.com/post/shou-ji/wen-zhang-dao-hang

Spring IOC knowledge point clean sweep!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.