[Chapter 3] Scope of DI 3.4 Bean: Learn from me Spring 3

Keywords: Spring Java Session Attribute

3.4 Scope of Bean s

What is scope? In object-oriented programming, "scope" generally refers to the visible range between objects or variables. In Spring containers, it refers to the visibility of the Bean objects it creates relative to the requests of other Bean objects.

Spring provides two basic scopes of "singleton" and "prototype", and three web scopes of "request", "session" and "global session". Spring also allows users to customize their scopes.

3.4.1 Basic Scope

Singleton: Beans with a "singleton" scope only have one instance in each Spring IoC container, and their full life cycle is completely managed by the Spring container. The Spring container will return only the same Bean for all operations that acquire the Bean.

 

GoF singleton design pattern refers to guaranteeing that a class has only one instance and providing a global access point to it. Two implementations are introduced: maintaining the instance by defining static attributes on the class and registry.

       

1) Maintaining the instance by defining static attributes on the class: generally speaking, a class loaded by a Java virtual machine ClassLoader has only one instance, and it is generally maintained by static attributes of the class, which results in that classes requiring singletons need to be coded according to the singleton design pattern; Spring does not use this method because it belongs to intrusive design; code samples, for example, are as follows:

 

java code:
  1. package cn.javass.spring.chapter3.bean;  
  2. public class Singleton {  
  3.     //1. Privatization constructor  
  4.     private Singleton() {}  
  5.     //2. Singleton cache, lazy initialization, initialization when first used  
  6.     private static class InstanceHolder {  
  7.         private static final Singleton INSTANCE = new Singleton();  
  8.     }  
  9.     //3. Providing global access points  
  10.     public static Singleton getInstance() {  
  11.         return InstanceHolder.INSTANCE;  
  12.     }  
  13.     //4. Provide a counter to validate a ClassLoader instance  
  14.     private int counter=0;  
  15. }  

 

 

The above definition of a singleton class first privatizes the class constructor; secondly, it uses InstanceHolder static inner class to hold singleton objects so as to gain the benefit of lazy initialization; finally, it provides the global access point getInstance so that objects requiring the singleton instance can be obtained; and here we also provide a counter counter to verify an instance of ClassLoader. Specifically, a ClassLoader has a single instance test. Refer to the "test Singleton" test method in the code "cn. javass. spring. chapter3. Singleton Test", which demonstrates in detail that a ClassLoader has a single instance.

 

 

1) Registry: First, the instance of the singleton will be registered in the registry through the unique key, and then the singleton will be obtained by the key. Let's look at the implementation directly. Note that this registry implements the Spring interface "Singleton Bean Registry", which defines the singleton object for operation sharing, and the Spring container implements this interface. "Register Singleton" method registration, through "get Singleton" method acquisition, eliminating programming singletons, note that concurrency is not considered in the implementation:

 

 

java code:
  1. package cn.javass.spring.chapter3;  
  2. import java.util.HashMap;  
  3. import java.util.Map;  
  4. import org.springframework.beans.factory.config.SingletonBeanRegistry;  
  5. public class SingletonBeanRegister implements SingletonBeanRegistry {  
  6.     //Single Bean Cache Pool, where concurrency is not considered  
  7.     private final Map<String, Object> BEANS = new HashMap<String, Object>();  
  8.     public boolean containsSingleton(String beanName) {  
  9.         return BEANS.containsKey(beanName);  
  10.     }  
  11.     public Object getSingleton(String beanName) {  
  12.         return BEANS.get(beanName);  
  13.     }  
  14.     @Override  
  15.     public int getSingletonCount() {  
  16.         return BEANS.size();  
  17.     }  
  18.     @Override  
  19.     public String[] getSingletonNames() {  
  20.         return BEANS.keySet().toArray(new String[0]);  
  21.     }  
  22.     @Override  
  23.     public void registerSingleton(String beanName, Object bean) {  
  24.         if(BEANS.containsKey(beanName)) {  
  25.             throw new RuntimeException("[" + beanName + "] Already exist");  
  26.         }  
  27.         BEANS.put(beanName, bean);  
  28. }  
  29. }  
  30.    

 

Spring is the implementation of registration form design pattern, eliminating programmable singletons and non-intrusive to code.

Next let's see how to configure a singleton in Spring. If the scope is not specified in Spring container, the default is "singleton". The configuration is configurated through the scope attribute. The configuration is as follows:

 

java code:
  1. <bean  class="cn.javass.spring.chapter3.bean.Printer" scope="singleton"/>  

 

Spring manages the storage of singleton objects in Spring containers as shown in Figure 3-5. Spring not only caches singleton objects, but also Bean definitions. For lazily initialized objects, they are created and stored in the singleton cache pool according to Bean definitions for the first time.

 

Figure 3-5 Singleton Processing

 

prototype: prototype means that every request to the Spring container for a Bean returns a brand-new Bean. Compared with "singleton", it does not cache a Bean, and each time it is a brand-new Bean created according to the definition of the Bean.

 

GoF prototype design pattern refers to specifying the types of objects created with prototype instances and creating new objects by copying these prototypes.

 

Prototypes in Spring and GoF have different meanings:

GoF specifies the type of object created by prototype instances, while the Spring container specifies the type of object created by Bean definitions.

GoF creates new objects by copying these prototypes, while the Spring container creates new objects based on Bean definitions.

The same thing is to create something new based on something, and the GoF prototype must show cloning operations, which belongs to intrusive, while the Spring container only needs configuration, which belongs to non-intrusive.

 

Now let's see how Spring implements prototypes.

 

1) Let's first define the Bean "prototype": Bean definition, all objects will be created according to the Bean definition; here we are just a simple example, not involving complex implementations such as dependency injection: BeanDefinition class defines attribute "class" for prototype class, id for unique identifier, scope for scope, as follows:

 

java code:
  1. package cn.javass.spring.chapter3;  
  2. public class BeanDefinition {  
  3.     //Single case  
  4.     public static final int SCOPE_SINGLETON = 0;  
  5.     //prototype  
  6.     public static final int SCOPE_PROTOTYPE = 1;  
  7.     //Unique identification  
  8.     private String id;  
  9.     //class full qualified name  
  10.     private String clazz;  
  11.     //Scope of action  
  12. private int scope = SCOPE_SINGLETON;  
  13.     //In view of space, the setter and getter methods are omitted.  
  14. }  

 

2) Let's look at the Bean definition registry, similar to the singleton registry:

 

java code:
  1. package cn.javass.spring.chapter3;  
  2. import java.util.HashMap;  
  3. import java.util.Map;  
  4. public class BeanDifinitionRegister {  
  5.     //Beans define caches, without considering concurrency here  
  6. private final Map<String, BeanDefinition> DEFINITIONS =  
  7.  new HashMap<String, BeanDefinition>();  
  8.     public void registerBeanDefinition(String beanName, BeanDefinition bd) {  
  9.         //1. Bean definitions are not allowed to be overwritten in this implementation  
  10.         if(DEFINITIONS.containsKey(bd.getId())) {  
  11.             throw new RuntimeException("Already exist Bean Definition, this implementation does not allow coverage");  
  12.         }  
  13.         //2. Put Bean Definitions into Bean Definition Cache Pool  
  14.         DEFINITIONS.put(bd.getId(), bd);  
  15.     }  
  16.     public BeanDefinition getBeanDefinition(String beanName) {  
  17.         return DEFINITIONS.get(beanName);  
  18.     }  
  19. public boolean containsBeanDefinition(String beanName) {        
  20.  return DEFINITIONS.containsKey(beanName);  
  21.     }  
  22. }  

 

3) It's time to define BeanFactory:

 

java code:
  1. package cn.javass.spring.chapter3;  
  2. import org.springframework.beans.factory.config.SingletonBeanRegistry;  
  3. public class DefaultBeanFactory {  
  4.     //Bean Definition Registry  
  5.     private BeanDifinitionRegister DEFINITIONS = new BeanDifinitionRegister();  
  6.    
  7.     //Singleton Registry  
  8.     private final SingletonBeanRegistry SINGLETONS = new SingletonBeanRegister();  
  9.      
  10.     public Object getBean(String beanName) {  
  11.         //1. Verify the existence of Bean definitions  
  12.         if(!DEFINITIONS.containsBeanDefinition(beanName)) {  
  13.             throw new RuntimeException("Non-existent[" + beanName + "]Bean Definition");  
  14.         }  
  15.         //2. Getting Bean Definitions  
  16.         BeanDefinition bd = DEFINITIONS.getBeanDefinition(beanName);  
  17.         //3. Whether the Bean definition is a singleton scope  
  18.         if(bd.getScope() == BeanDefinition.SCOPE_SINGLETON) {  
  19.             //3.1 If the singleton registry contains a Bean, return the Bean directly  
  20.             if(SINGLETONS.containsSingleton(beanName)) {  
  21.                 return SINGLETONS.getSingleton(beanName);  
  22.             }  
  23.             //3.2 The Bean is not included in the singleton registry.  
  24.             //Create and register a singleton registry to cache  
  25.             SINGLETONS.registerSingleton(beanName, createBean(bd));  
  26.             return SINGLETONS.getSingleton(beanName);  
  27.         }  
  28.         //4. If it is a prototype Bean definition, it directly returns the new Bean created according to the Bean definition.  
  29. //Every time it's new, no cache  
  30.         if(bd.getScope() == BeanDefinition.SCOPE_PROTOTYPE) {  
  31.             return createBean(bd);  
  32.         }  
  33.         //5. Bean Definition Wrong in Other Cases  
  34.         throw new RuntimeException("FALSE Bean Definition");  
  35.     }  
  36.    

 

 

java code:
  1. public void registerBeanDefinition(BeanDefinition bd) {  
  2.      DEFINITIONS.registerBeanDefinition(bd.getId(), bd);  
  3.  }  
  4.   
  5.  private Object createBean(BeanDefinition bd) {  
  6.      //Create Beans Based on Bean Definitions  
  7.      try {  
  8.          Class clazz = Class.forName(bd.getClazz());  
  9.          //Creating Bean s by Reflecting Using a Parametric-Free Constructor  
  10.          return clazz.getConstructor().newInstance();  
  11.      } catch (ClassNotFoundException e) {  
  12.          throw new RuntimeException("Can't find Bean[" + bd.getId() + "]class");  
  13.      } catch (Exception e) {  
  14.          throw new RuntimeException("Establish Bean[" + bd.getId() + "]fail");  
  15.      }  
  16.  }  

 

The method getBean is used to get the object created according to the Bean definition of the beanName. There are two types of beans: singleton and prototype; registerBean Definition is used to register the Bean definition; and the private method createBean is used to create beans according to the type information in the Bean definition.

 

3) Test it. Here we only test prototype scope beans, which are a brand new object for each bean retrieved from the bean factory. The Bean FatoryTest is as follows:

 

java code:
  1. @Test  
  2. public void testPrototype () throws Exception {  
  3. //1. Create Bean Factory  
  4. DefaultBeanFactory bf = new DefaultBeanFactory();  
  5. //2. Creating Prototype Bean Definition  
  6. BeanDefinition bd = new BeanDefinition();  
  7. bd.setId("bean");  
  8. bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);  
  9. bd.setClazz(HelloImpl2.class.getName());  
  10. bf.registerBeanDefinition(bd);  
  11. //For prototype beans, you should return a brand new Bean at a time  
  12. System.out.println(bf.getBean("bean") != bf.getBean("bean"));  
  13. }  

 

 

Finally, let's see how to configure it in Spring by specifying the < bean > tag attribute "scope" attribute as "prototype":

 

java code:
  1. <bean class="cn.javass.spring.chapter3.bean.Printer" />  

 

 

Spring manages prototype objects stored in Spring containers as shown in Figure 3-6. Spring does not cache prototype objects, but returns a brand new bean per request according to the Bean definition:

 

Figure 3-6 Prototype Processing

Now that we've covered the singleton and prototype scopes, let's learn some scopes for Web applications:

 

3.4.2 Scope in Web Applications

In Web applications, we may need to store data into request s, session s, and global Session. So Spring provides three Web scopes: request, session, and global Session.

 

Request scope: Indicates that each request requires a container to create a brand new Bean. For example, the data submitting a form must be a new bean for each request to maintain the form data, and the request ends to release the data.

 

Session scope: Indicates that each session requires a container to create a brand new Bean. For example, for each user, there is usually a session, and the user information of that user needs to be stored in the session. At this time, the bean can be configured as a web scope.

 

globalSession: Similar to session scope, it is only a web application for portlet environment. If it is in a non-portlet environment, it will be considered session scope.

 

Configuration is the same as the basic scopes, but you have to have web environment support, and configure the corresponding container listener or interceptor to apply these scopes. We will explain how to use them when integrating the web. You just need to know these scopes.

 

3.4.4 Custom Scope

In daily program development, almost no custom scope is needed, unless it is necessary to do so.

Let's first look at the Scope interface:

 

java code:
  1. package org.springframework.beans.factory.config;  
  2. import org.springframework.beans.factory.ObjectFactory;  
  3. public interface Scope {  
  4.        Object get(String name, ObjectFactory<?> objectFactory);  
  5.        Object remove(String name);  
  6.        void registerDestructionCallback(String name, Runnable callback);  
  7.        Object resolveContextualObject(String key);  
  8.        String getConversationId();  
  9. }  

 

1) Object get (String name, ObjectFactory <?> objectFactory): Used to get beans from scope, where the parameter objectFactory is used to create a new Bean when the appropriate Bean is not found in the current scope;

 

2) Void register Destruction Callback (String name, Runnable callback): Used to register destroy callback, if you want to destroy the corresponding object, the Spring container registers the corresponding destroy callback, and the custom scope chooses whether to destroy the corresponding object;

 

3) Object resolveContextualObject(String key): Used to parse the corresponding context data, such as the request scope returns the attributes in the request.

 

4) String getConversation Id (): Session identifiers for scopes, such as session scopes, will be session Id.

 

 

java code:
  1. package cn.javass.spring.chapter3;  
  2. import java.util.HashMap;  
  3. import java.util.Map;  
  4. import org.springframework.beans.factory.ObjectFactory;  
  5. import org.springframework.beans.factory.config.Scope;  
  6. public class ThreadScope implements Scope {  
  7. private final ThreadLocal<Map<String, Object>> THREAD_SCOPE =  
  8. new ThreadLocal<Map<String, Object>>() {  
  9.       protected Map<String, Object> initialValue() {  
  10.           //Used to store thread-related beans  
  11.           return new HashMap<String, Object>();  
  12.       }  
  13.     };  

 

Let's implement a simple thread scope in which objects created are bound to ThreadLocal.

      

java code:
  1.     @Override  
  2.     public Object get(String name, ObjectFactory<?> objectFactory) {  
  3.         //If the current thread has bound the corresponding Bean, return directly  
  4.         if(THREAD_SCOPE.get().containsKey(name)) {  
  5.            return THREAD_SCOPE.get().get(name);  
  6.         }  
  7.         //Create beans using objectFactory and bind them to the current thread  
  8.         THREAD_SCOPE.get().put(name, objectFactory.getObject());  
  9.         return THREAD_SCOPE.get().get(name);  
  10.     }  
  11.     @Override  
  12.     public String getConversationId() {  
  13.         return null;  
  14.     }  
  15.     @Override  
  16.     public void registerDestructionCallback(String name, Runnable callback) {  
  17.         //If it's not implemented here, it's proytotype-like. When the container is returned to the user, it doesn't matter.  
  18.     }  
  19.     @Override  
  20.     public Object remove(String name) {  
  21.         return THREAD_SCOPE.get().remove(name);  
  22.     }  
  23.     @Override  
  24.     public Object resolveContextualObject(String key) {  
  25.         return null;  
  26.     }  
  27. }  
  28.    

 

Scope has been implemented, so let's register it with the Spring container to make it work:

 

java code:
  1. <bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">  
  2.         <property name="scopes">  
  3.            <map><entry>  
  4.                    <!-- Appoint scope Keyword --><key><value>thread</value></key>  
  5.                    <!-- scope Realization -->      <bean class="cn.javass.spring.chapter3.ThreadScope"/>  
  6.            </entry></map>      
  7.         </property>  
  8.     </bean>  

 

CustomScopeConfigurer registers a custom scope implementation through the scope attribute of CustomScopeConfigurer, where you need to specify the keyword "thread" that uses the scope and specify the custom scope implementation. Let's define a "thread" scoped Bean with the following configuration (chapter3/threadScope.xml):

 

java code:
  1. <bean id="helloApi"  
  2.     class="cn.javass.spring.chapter2.helloworld.HelloImpl"  
  3.     scope="thread"/>  

 

Finally, let's test (cn.javass.spring.chapter3.ThreadScopeTest). First, test in one thread, and get the same Bean in the same thread. Then let's open two threads, and then the beans created by the two threads are different:

 

 

The implementation of custom scopes is actually very simple, but the complexity is how to correctly destroy beans if you need to destroy beans.

 

Please indicate the origin of the original content reprinted[ http://sishuok.com/forum/blogPost/list/2454.html]

Posted by Alka-Seltxer on Sat, 30 Mar 2019 04:45:30 -0700