Spring learns the configuration items and scopes of bean configuration for four----------beans

Source: Internet
Author: User

The scope of the bean (each scope is in the same bean container)

1.singleton: Singleton, refers to only one copy in a bean container (default)

2.prototype: Create a new instance per request (per use), Destory mode does not take effect

3.request: Each HTTP request creates an instance and only takes effect within the current request ( only available in the Web )

4.session: Ditto, each HTTP request creates an instance that is valid within the current session ( only available in the Web )

5.global session: Portlet-based Web is valid (the Portlet defines the global session), if it is in a single web, the same session. ( can only be used in the Web )

Instance

1.singleton and prototype

1.1 Directory Structure

1.2 Pom.xml

<project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" >< Modelversion>4.0.0</modelversion><groupid>org.spring</groupid><artifactid>spring </artifactid><version>0.0.1-snapshot</version><packaging>jar</packaging><name >Spring</name><url>http://maven.apache.org</url><properties>< Project.build.sourceencoding>utf-8</project.build.sourceencoding><spring.version>4.3.7.release </spring.version></properties><dependencies><!--JUnit Dependent--><dependency>< Groupid>junit</groupid><artifactid>junit</artifactid><version>4.12</version> <scope>test</scope></dependency><!--Spring relies on--><dependency> <groupId> Org.springframework</groupid> <Artifactid>spring-core</artifactid> <version>${spring.version}</version></dependency ><dependency> <groupId>org.springframework</groupId> <artifactid>spring-beans</ Artifactid> <version>${spring.version}</version></dependency><dependency> <groupid >org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${ Spring.version}</version></dependency></dependencies></project>

1.3 Spring-beanscope.xml (scope= "Singleton" | | Scope= "Prototype")

<?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=" Beanscope " class= "Org.spring.bean.BeanScope" scope= "singleton"/>                </beans>

1.4 Beanscope.java

Package Org.spring.bean;public class Beanscope {public void Say () {System.out.println ("hashcode:" + this.hashcode ());// Determine if it is the same instance by Hashcode}}

1.5 Unittestbase.java

Package Org.spring.ioc.test;import Org.junit.after;import Org.junit.before;import Org.springframework.context.support.classpathxmlapplicationcontext;import org.springframework.util.StringUtils ;/** * Unit Test Initialization class * */public class Unittestbase {private Classpathxmlapplicationcontext context;private String Springxmlpat h;/** * Parameterless Constructor */public Unittestbase () {}/** * with parameter constructor * * @param springxmlpath * Spring config file path */public unittestbase (String Springxmlpath) {This.springxmlpath = Springxmlpath;} /** * Initialize Spring config file */@Before//Execute public void before () {if (Stringutils.isempty (Springxmlpath)) {///before @test annotation method execution) Default Spring configuration file path Springxmlpath = "Classpath*:spring-*.xml";} Load configuration file, a context represents a container context = new Classpathxmlapplicationcontext (Springxmlpath.split ("[, \\s]+"));// Boot component Context.start ();} /** * Destroy Spring Component */@After//Execute public void after () {Context.destroy () when @test annotation method executes,//Destroy component}/** * Get bean instance defined in Spring * * @pa Ram Beanid * * @return */@SuppressWarnings ("unchecked") protected <t extends object> T getbeaN (String Beanid) {return (T) Context.getbean (Beanid);} /** * Gets the bean instance defined in Spring * * @param clazz * * @return */protected <t extends object> T Getbean (class<t> Claz Z) {return (T) Context.getbean (Clazz);}}

1.6 Testbeanscope.java

Package Org.spring.ioc.test;import Org.junit.test;import Org.junit.runner.runwith;import Org.junit.runners.blockjunit4classrunner;import org.spring.bean.BeanScope; @RunWith (blockjunit4classrunner.class )//Specify JUnit Default execution class public classes Testbeanscope extends Unittestbase {public testbeanscope () {//Pass the constructor method to the spring configuration file path Super (" Classpath*:spring-beanscope.xml ");} @Testpublic void Testscope () {Beanscope beanscope = Super.getbean ("Beanscope"); Beanscope.say ()/** * If you execute both lines of code in two methods, The hashcode will be different. * Because @before is executed before each test method executes, the spring configuration file is reloaded, at this time in two containers, so the different */beanscope beanScope2 = Super.getbean ("Beanscope"); Beanscope2.say ();}}

1.7 Singleton Effect Preview

1.8 Prototype Effect Preview

2.request and Session

2.1 Project Structure

  2.2 Pom.xml

<project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" ><modelversion >4.0.0</modelversion><groupid>org.spring</groupid><artifactid>springbeanscope</ Artifactid><packaging>war</packaging><version>0.0.1-snapshot</version><name> Springbeanscope Maven webapp</name><url>http://maven.apache.org</url><properties>< spring.version>4.3.7.release</spring.version></properties><dependencies><!--JUnit Dependency- > <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <vers Ion>4.12</version> <scope>test</scope> </dependency> <!--spring Core dependent-->< Dependency> <groupId>org.springframework</groupId> <artifactid>spring-core&Lt;/artifactid> <version>${spring.version}</version></dependency> <!--Spring Web layer Dependent-- <dependency> <groupId>org.springframework</groupId> <artifactid>spring-webmvc</ artifactid> <version>${spring.version}</version></dependency><!--Jstl-->< dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> &LT;VERSION&GT;1.2&L t;/version></dependency><!--servlet--><dependency> <groupid>javax.servlet</ Groupid> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version></ dependency></dependencies> <build> <finalName>springBeanScope</finalName> </build&  Gt </project>

2.3 Mvc-dispatcher-servlet.xml

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "Http://www.springframework.org/schema/context" Xmlns:mvc= "Http://www.springframework.org/schema/mvc" xsi:schemalocation= "Http://www.springframework.org/schema /beans http://www.springframework.org/schema/beans/spring-beans.xsd Http://www.springframework.org/schema/co ntext http://www.springframework.org/schema/context/spring-context.xsd Http://www.springframework.org/schema /mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd "> <!--Open Package Scan--&LT;CONTEXT:C  Omponent-scan base-package= "org.spring.*"/> <!--opening annotations-<mvc:annotation-driven/> <!-- Define the View resolver--<bean id= "Viewresolver" class= "Org.springframework.web.servlet.view.InternalResourceViewResolver "> <property name=" prefix "value="/web-inf/jsp/"/> <property name= "suffix" value= ". jsp"/> </bean> </beans> 

2.4 Beanscope.xml

Package Org.spring.bean;public class Beanscope {public int say () {return this.hashcode ();//The same instance is determined by the returned Hashcode)}

2.5 spring.xml

<?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=" Beanscope "class=" Org.spring.bean.BeanScope "scope=" singleton "/>        </beans>

2.6 Web

<?xml version= "1.0" encoding= "UTF-8"? ><web-app xmlns= "Http://java.sun.com/xml/ns/javaee" xmlns:xsi= "http ://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation=" Http://java.sun.com/xml/ns/javaee/http Java.sun.com/xml/ns/javaee/web-app_3_0.xsd "version=" 3.0 "metadata-complete=" true "> <!--start the spring listener, Load Applicationcontext.xml By default--<listener> <listener-class> Org.springframework.web.context.contextloaderlistener</listener-class> </listener> <!-- Customize the Spring Profile path-<context-param> <param-name>contextConfigLocation</param-name> <  Param-value>classpath:spring.xml</param-value> </context-param> <!--intercept all requests and leave them with SPRINGMVC <servlet> <servlet-name>springMVC</servlet-name> <servlet-class> Org.springframework.web.servlet.dispatcherservlet</servlet-class> <init-param> <param-name> Contextconfiglocation</param-name>  <param-value>classpath:mvc-dispatcher-servlet.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>/</url-pattern > </servlet-mapping> </web-app>

2.7 Beanscopeaction.java

Package Org.spring.action;import Java.util.arraylist;import Java.util.list;import javax.servlet.http.HttpSession; Import Org.spring.bean.beanscope;import Org.springframework.beans.beansexception;import Org.springframework.context.applicationcontext;import Org.springframework.context.ApplicationContextAware; Import Org.springframework.stereotype.controller;import Org.springframework.ui.modelmap;import Org.springframework.web.bind.annotation.RequestMapping, @Controllerpublic class Beanscopeaction implements Applicationcontextaware {private ApplicationContext context; @RequestMapping ("/") public String Testscope (Modelmap map , HttpSession session) {Beanscope scope = (beanscope) context.getbean ("Beanscope"); list<integer> list = new arraylist<integer> (); for (int i = 0; i < 3; i++) {List.add (Scope.say ());} Map.addattribute ("list", list), Map.addattribute ("session", session); return "Scope";} public void Setapplicationcontext (ApplicationContext context) throws Beansexception {This.context= Context;}} 

2.8 scope.jsp

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "    pageencoding=" UTF-8 "%><%@ taglib prefix=" C "uri=" Http://java.sun.com/jsp/jstl/core "%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >

2.9 Effect Preview

Need to refresh to see the effect, the expression is not clear, you can copy code to run the Refresh view results.

3.global session

Multiple items are required to see the results, and no tests are done here.

Reference: http://www.imooc.com/video/3750/

Spring learns the configuration items and scopes of bean configuration for four----------beans

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.