Spring Bean of the definition, the scope

  Bean object is called the basic configuration of the application is managed by the Spring IOC container, but for a Bean properties typically contains about:

Attributes description
class The fully qualified name of the attribute is mandatory, and specifies the bean class to create the bean.
name This attribute specifies the unique identifier bean. XML-based metadata configuration, you can use the ID and / or name attribute to specify the bean identifier.
scope This attribute specifies the object created by the special bean definitions of scope, it will be discussed in chapter bean in scope.
constructor-arg It is used dependency injection, and will be discussed in the next sections.
properties It is used dependency injection, and will be discussed in the next sections.
autowiring mode It is used dependency injection, and will be discussed in the next sections.
lazy-initialization mode Lazy Initialization of bean told IoC container when it is first requested, rather than to create a bean instance when it starts.
initialization method After all the necessary properties of the bean container is set, call the callback method. It will be discussed chapter in the life cycle of the bean.
destruction method When the container containing the bean is destroyed, using the callback method. It will be discussed chapter in the life cycle of the bean.

  Bean identifier may not display the configuration, Spring will default hump according to standard nomenclature Bean set identifier, such as accountService, userDao Bean object based on the name and the like; however, in the (unusual) special circumstances, If there is more than one character, and the first and second characters are uppercase, then retain the original case.

  Bean scopes

  When defining a bean in the Spring, you have the option to scope the bean statement. For example, to enforce Spring has produced a new bean instance every time you need, you should declare the scope of the bean property for the  prototype . Similarly, if you want Spring every time you need to return all the same bean instance, you should declare the scope of the bean property for  Singleton .

  Spring Framework supports the following five scopes, respectively singleton, prototype, request, session, and global session, 5 Species scope described below, note that if you are using the web-aware ApplicationContext, three of which are available.

  

Scope description
singleton

In the spring IoC container exists only one example Bean, Bean manner in the presence of a single embodiment, the default value

prototype Each time the call Bean, returns a new instance of the container, i.e., each call to the getBean (), equivalent to the implementation newXxxBean () 
request Each HTTP request will create a new Bean, that scope applies only to the environment WebApplicationContext
session Share a same HTTP Session Bean, different Session using different Bean, applies only to the environment WebApplicationContext
global-session Portlet applications for the general environment, the use of domain applies only to the environment WebApplicationContext

  The following will be discussed using the former two scopes. For testing purposes, we need to re-create a POJO (LifeScope.java) and test methods, as follows:

/**
 * @author johnson liu
 * @description Bean的生命周期测试POJO类
 */
public class LifeScope {
    private String name;

    public void getName(int num) {
        System.out.println("Your name :"+name+">>>"+num);
    }
    public void setName(String name) {
        this.name = name;
    }
}

  Define the interface and its implementation class LifeService.java LifeServiceImpl.java:

package scope;

import quickstart.LifeScope;

public interface LifeService {
    /**
     *
     * @param lifeScope 作用域测试
     */
    void setLife(LifeScope lifeScope);

    LifeScope getLife();
}
package scope;

import quickstart.LifeScope;
/**
 * @author johnson liu
 * @description Bean生命周期测试
 */
public class LifeServiceImpl implements LifeService {

    private LifeScope lifeScope;
    /**
     * @param lifeScope 作用域测试
     */
    public void setLife(LifeScope lifeScope) {
        this.lifeScope=lifeScope;
    }
    public LifeScope getLife(){
        return this.lifeScope;
    }
}

  To test instantiated Bean Spring container is a single case or multiple cases, you also need to create a simple multi-threaded class to test (by multiple threads, we can get multiple instances of the implementation class, output this instance, if the reference instance of an object address as it is a singleton, otherwise belong to multiple cases; secondly, in order to differentiate between the different usage of these two models, the interior threads num private variables created as a way to distinguish which thread output):

package scope;

import org.springframework.context.ApplicationContext;
import quickstart.LifeScope;

import java.util.Random;
/**
 * @author johnson liu
 * @description
 */
public class LifeThread extends Thread {
    private ApplicationContext context;
    private LifeScope lifeScope;
    private Integer num;
    public LifeThread(){
    }
    public LifeThread(int num,ApplicationContext context,LifeScope lifeScope){
        this.context=context;
        this.lifeScope=lifeScope;
        this.num=num;
    }
    @Override
    public void run() {
        long time=(long)(Math.random()*1000+1);
        try {
            LifeServiceImpl lifeService=((LifeServiceImpl)context.getBean("lifeService"));
            System.out.println(lifeService);
            lifeService.setLife(lifeScope);
            Thread.sleep(time);
            LifeScope returnLifeScope= lifeService.getLife();
            returnLifeScope.getName(num);
        }catch (Exception e){

        }
    }
}

  Configuring Beans.xml, let LifeServiceImpl be managed by the Spring container:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="helloWorld" class="quickstart.HelloWorld">
        <!--<constructor-arg name="message" value="使用xml进行构造函数注入"></constructor-arg>-->
        <property name="message" value="hello world"></property>
    </bean>

    <!--<bean id="lifeService" class="scope.LifeServiceImpl" scope="prototype"></bean>-->
    <bean id="lifeService" class="scope.LifeServiceImpl" scope="singleton"></bean>

</beans>

  Write test code:

Package QuickStart; 

Import org.springframework.context.ApplicationContext;
 Import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 Import org.springframework.context.support.ClassPathXmlApplicationContext;
 Import org.springframework.context.support.FileSystemXmlApplicationContext;
 Import scope.LifeServiceImpl;
 Import scope.LifeThread; 

public  class MainTest { 

    public  static  void main (String [] args) {
         / ** 
         * the ApplicationContext is an interface, Spring responsible for reading configuration file, loading management object generated; Bean object and maintaining the object Bean between the dependency responsible for Bean's life cycle.
         * ClassPathXmlApplicationContext, FileSystemXmlApplicationContext, AnnotationConfigApplicationContext like are ApplicationContext interface implementation class 
         * for reading the ClassPathXmlApplicationContext Spring configuration file from the classpath 
         * a FileSystemXmlApplicationContext from the file system for loading application contexts 
         * AnnotationConfigApplicationContext for loading the application context from the Java class 
         * / 
        the ApplicationContext context = new new the ClassPathXmlApplicationContext ( "beans.xml"); // from the class path loading application contexts
 //         the ApplicationContext a FileSystemXmlApplicationContext new new context = ( "D: \\ IdeaProjects Spring \\ \\ \\ Java Core the src \\ \ \ \\ Resources \\ main beans.xml "); // from the file system to load an application context
         //ApplicationContext context=new AnnotationConfigApplicationContext("quickstart");//从Java类中加载应用上下文
        /*HelloWorld helloWorld=(HelloWorld)context.getBean("helloWorld");
        helloWorld.getMessage();*/

        LifeServiceImpl lifeService=(LifeServiceImpl)context.getBean("lifeService");
        LifeScope lifeScope1=new LifeScope();
        lifeScope1.setName("Scope测试1");

        LifeScope lifeScope2=new LifeScope();
        lifeScope2.setName("Scope测试2");

        LifeScope lifeScope3=new LifeScope();
        lifeScope3.setName("Scope测试3");

        LifeScope lifeScope4=new LifeScope();
        lifeScope4.setName("Scope测试4");

        LifeScope lifeScope5=new LifeScope();
        lifeScope5.setName("Scope测试5");

        LifeScope lifeScope6=new LifeScope();
        lifeScope6.setName("Scope测试6");

        new LifeThread(1,context,lifeScope1).start();
        new LifeThread(2,context,lifeScope2).start();
        new LifeThread(3,context,lifeScope3).start();
        new LifeThread(4,context,lifeScope4).start();
        new LifeThread(5,context,lifeScope5).start();
        new LifeThread(6,context,lifeScope6).start();
    }
}

  At this time, we are using the singleton scope, the test results are as follows:

  Can be found from the test results, Bean instance of the object that we have obtained the same object, but the output after the bean instance of an object by assigning private property, its value is not the value obtained by the current thread settings. Here we look at the scope of the bean as a result of the modification scope = "prototype":

<the bean ID = "lifeService" class = "scope.LifeServiceImpl" scope = "the prototype"> </ the bean> // This line will be canceled in the above comments beans.xml

  From the above test results we found in multi-threaded, multi-pattern is thread-safe. Typically such a private property of the Bean Bean containing globally, we call stateful Bean, and vice versa for stateless Bean. 
  Therefore, for this type of stateful bean when defining, we certainly want to declare its scope as prototype mode.

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/onedayinMay/p/12501203.html