Spring beans are scoped to four types: Singleton, prototype, session, and request.
There are two kinds of singleton and prototype commonly used. The other two are less of a use
Use the bean's scope property to configure the scope of the bean
Singleton: Default value. A bean instance is created when the container is initialized, and only one bean is created during the lifetime of the container, in the case of a singleton.
Prototype: prototype, container initialization does not create a bean instance, and a new bean instance is created and returned on each request.
For example:
Car.java:
Package Com.ksk.spring;public class Car {private String brand; Private String Corp; private int price; private int maxspeed; public void Setbrand (String brand) {This.brand = brand; } public void Setprice (int price) {this.price = Price; } public Car () {System.out.println ("init ...."); }}
Beans-scope.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 "> <!-- Use the bean's scope property to configure the Bean's scope singleton: Default value. A bean instance is created when the container is initialized, and only one bean is created during the lifetime of the container, in the case of a singleton. prototype: Prototype, container initialization does not create a bean instance, and a new bean instance is created and returned on each request. --> <bean id= "Car" class= " Com.ksk.spring.Car " scope=" Singleton "> <property name= "brand" value= "Audi" ></property> < Property name= "Price" value= "30000 "></property> </bean></beans>
Main.java:
Package com.ksk.spring.beans.scope;import org.springframework.context.applicationcontext;import org.springframework.context.support.classpathxmlapplicationcontext;import com.ksk.spring.car;public class Main { public static void Main (String[] args) { applicationcontext ctx = new classpathxmlapplicationcontext ("Beans-scope.xml");// Car car = (CAR) ctx.getbean ("Car");// Car car2 = (CAR) ctx.getbean ("Car");// // system.out.println (CAR);// system.out.println (CAR2);// // system.out.println (car==car2); }} when Scope= "singleton", the output is true when Scope= " Prototype ", the output is false.
This article from "My Youth I Master" blog, declined reprint!
Spring4 Learning: The scope of a bean