3、 ... and 、 Dependency injection object Scope And its life cycle

In the previous chapter we talked about , The reason why dependency injection containers can be different from the past ServiceLocator Equal container , The reason is that it can not only automatically build multi-level 、 Complete dependency graph , And you can manage objects that depend on Scope And behavioral reinforcement . We'll talk about behavioral reinforcement in the next chapter , Let's look at the dependency object first Scope And life cycle management .

1.      Dependency injection object Scope

Scope, Scope , It refers to the lifetime of a class of objects designed in object-oriented development . Let's start with the ordinary Java Singleton and stateless are the two most commonly used in program development Scope Starting with , I'll talk about it later Web There are several common problems in application development Scope.

1.1.     Singleton and stateless Scope

No state Scope It's the simplest 、 The one with the shortest life span Scope, We all passed new All the non static objects that come out belong to this Scope, It goes with the object that uses this object ( It could be a dependency class , It could also be a method in the dependency class ) The death of the world . conversely , The single case is the one with the longest survival period Scope, It lives in a static mode JVM Of “ Old age region ”, Never be JVM Recycling . For example, we must have written or used singleton patterns like this :

public class BankICBC implements Bank {

private static Bank bankICBC; // bankICBC For a static singleton

private BankICBC() {} // Private constructor , So that the outside world can't directly new It's the object

public static Bank Instance() {

return null == bankICBC ? new BankICBC() : bankICBC; // Create a singleton object

}

// ……

}

Let's also use our example of withdrawal , Suppose that the passbook type used by the depositor is certificate of deposit , After the withdrawal, the bank will take back the certificate of deposit , In this case, for the passbook dependence of each withdrawal , It's all a stateless , That is to say, you need a new passbook every time you withdraw money , So at this time, the passbook is a stateless dependency . Let's assume that there is only one bank near the depositor , That is to say, whenever I withdraw money, I will go to the same bank , At this time, the bank is a single example of dependence , Every time you execute withDraw The method is to use the same bank dependent object .

Before the dependency injection framework , We create stateless passbook dependency and singleton bank dependency , It may be used separately new And the static way .new We have already discussed many problems of the mode in the first chapter . The static way also has the burden of developer management JVM Global variables are inconvenient or easy to cause memory leakage and many other problems . Dependency injection framework can help developers manage these Scope Dependence , Make developers get different Scope The dependency object becomes very simple and doesn't need to maintain it by itself .

Now let's Seam Framework as an example to illustrate how to define these two Scope.Spring、Guice Framework has a very similar definition , No more specific examples .

@Name("bank")

@Scope(ScopeType.APPLICATION) // Declare as a singleton Scope

public class BankICBC implements
Bank { // ……  }

@Name("depositBook")

@Scope(ScopeType.STATELESS) // Declare stateless Scope

public class DepositBookICBC
implements DepositBook { // …… 
}

Note that in the dependency injection framework , So-called “ Single case ” It's not a single case in the traditional sense , It is not JVM The only static variable that exists in , Instead, it injects the container as a dependency (Injector) Is the only non static variable in a unit , So as to avoid too much occupation JVM The memory of the old age area .

Dependency injection and AOP sketch ( Nine )—— Singleton and stateless Scope . More articles about

  1. Dependency injection and AOP sketch ( Ten )——Web Commonly used in development Scope brief introduction .

    1.2.    Web Commonly used in development Scope brief introduction This paper mainly introduces the concept based on Servlet Of Web Commonly used in development Scope. l         The first common one is Application level Scope, Usually we put a ...

  2. Dependency injection and AOP sketch ( 3、 ... and )—— The principle of dependency injection

    3.     “ Dependency injection ” On stage So many excellent IT Engineers began to come up with a lighter, more convenient . More testable and maintainable design patterns ——IoC Pattern .IoC, namely Inversion of Control Abbreviation , It's called in Chinese ...

  3. Dependency injection and AOP sketch ( Twelve )—— Behavior enhancement of dependency injection objects (AOP) .

    Four . Behavior enhancement of dependency injection objects (AOP) As mentioned earlier , The most distinctive feature of dependency injection framework is that it can provide dependent objects managed by containers , And it can provide behavior enhancement for objects (AOP) function , So in this chapter we're going to talk about AOP The topic of . 1.    ...

  4. Dependency injection and AOP sketch ( 5、 ... and )—— Dependency injection .

    Two . The application mode of dependency injection We learned the basic concepts of dependency injection , Some dependency injection frameworks are also introduced , In this chapter, we mainly discuss how to use the dependency injection framework as a developer to realize the design idea of dependency injection . 1.      The side of dependency injection ...

  5. Dependency injection and AOP sketch ( One )——“ rely on ” The concept of .

    One . introduction : Dependency injection As a new concept of design pattern ,“ Dependency injection ” This word has become more and more familiar in software design and development , And all kinds of popular in the open source community “ Dependency injection framework ”, It is also more and more used as the basic framework in the process of software engineering development . ...

  6. Dependency injection and AOP sketch ( 13、 ... and )——AOP Application, for example, ( The end ) .

    2.     AOP Application, for example, In general application development , There are some typical AOP application , So that developers can focus on the business logic itself , Rather than something totally unrelated to it “ aspect ”. l         The first is about the log output class described above ...

  7. Dependency injection and AOP sketch ( 7、 ... and )——FQCN Request mode

    2.2.    FQCN Request mode To make up for the type safety problem in the pure string request mode , Full class name (FQCN) The request mode came into being . The idea is , When requesting dependent objects from the container , Not through the identifier of a string . It's through the requested dependency ...

  8. Dependency injection and AOP sketch ( 6、 ... and )—— String request mode .

    2.      The request pattern of dependency injection objects In the previous section, we discussed several ways to declare injection points , This section mainly introduces how to locate the required identifier on the injection point . Basically , We can use strings as identifiers to request dependent objects . Or use the full class name ( ...

  9. Dependency injection and AOP sketch ( Four )——“ Hollywood principle ” And dependency injection framework .

    3.2.    “ Hollywood principle ” Looking at the previous description of the concept of dependency injection , Let's refine the core idea of dependency injection . If we say the traditional way of coupling between components , for example new. Factory mode, etc , It's a way for developers to take the initiative to build dependent objects , So dependency injection modules ...

Random recommendation

  1. iOS Super full open source framework 、 Project and learning materials summary (5)AppleWatch、 Classic blog 、 Third party open source summary

    Complete project v2ex – v2ex The client of , Journalism . Forum .apps-ios-wikipedia – apps-ios-wikipedia client .jetstream-ios – a Uber Of MV ...

  2. C++ Analysis of several important methods of multithreading CreateEvent / SetEvent /ResetEvent/ etc.

    1.CreateEvent  Is to create windows The meaning of the event , It is mainly used to judge thread exit , In terms of locking . Function description : Create or open a named or unnamed event object . HANDLE m_hExit; m_hExit= ...

  3. FPGA introduction 1

    FPGA Introduction to introductory knowledge    in recent years , Because of the field programmable gate array (FPGA) It's very flexible , And you can program infinitely , It has been loved by more and more electronic programmers , Many friends want to learn some FPGA Getting ready for the industry , It's off now ...

  4. Spinner Choose from the drop-down list , monitor ID After the display is different Frgment page

    I Android Xiaobai , The company's recent projects require different types of user registration , Write a record on the weekend afternoon . I found a lot of things on the Internet that are not suitable for me ( Or I didn't find ), The comparative basis of writing , Welcome to give more guidance . Old rules , First on the renderings Online synthesis of GIF ...

  5. About the terrain altas To deal with

    A few days ago, I was talking about the terrain with people in the group atlas The problem of , because Blade It's also used 4x4 Of atlas(16 Zhang texture ), But it was done about a few years ago , So some details are forgotten , Make a note here . 1.atlas It's the atlas , Atlas , Make multiple textures ...

  6. Yunqi Cloud Town Computing Conference day2 summary In the morning

    The next morning, I mainly participated in the developer special show On 09:00-09:40 The growth of engineers in the era of online and offline Integration Li Pei Hungry? Senior algorithm Director 09:40-10:20 How to unify Alibaba code specification : Explore the road of engineer culture stony-faced Ariba ...

  7. Scala Of apply unapply unapplySeq Grammatical sugar

    apply It can be understood as injecting unapply unapplySeq It can be understood as extracting  apply And unapply Although the names are similar , But it's quite different in use .apply It's kind of like a constructor unapply It's mainly the combination mold ...

  8. GenomicConsensus (quiver, arrow) Usage method | Sequence consensus

    https://github.com/PacificBiosciences/GenomicConsensus GenomicConsensus yes pacbio Developed , I personally don't like pacbio Developed ...

  9. PHPActiveRecord Study three

    # Transaction processing Pay attention to the business Database to use InnoDB engine $c1 = User::connection(); try { // Open transaction $c1->transaction(); //sql sentence $sql ...

  10. [A Class meeting ] Domestic paper retrieval

    https://www.cn-ki.net/ http://www.koovin.com