Home » Java » Spring object scope

Spring object scope

- Start

By default, Spring will create the object cache in the container, when we need a Spring object when a cached object is returned to the US, and will not create a new object, if you want to make Spring each time you return a new object to do? Take a look at the following example:.


package shangbo.spring.example7;
Public class {OutPutService
Public void (outPut) {
System.out.println ("Hello World");
}
}

?
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 ">
Scope specifies the object scope, support the following values
The default value is singleton
Prototype always returns a new object
Request available under Web
Session available under Web
GlobalSession available under Web
Application available under Web
Websocket available under Web
-- >
Scope = "prototype" / >

package shangbo.spring.example7;
Import org.springframework.context.ApplicationContext;
Import org.springframework.context.support.ClassPathXmlApplicationContext;
Public class App
{
Public static void main (String[] args)
{
/ / instantiate the Spring IoC container
ApplicationContext context = new ClassPathXmlApplicationContext ("shangbo/spring/example7/example.xml");
/ / get a OutPutService object from the container
OutPutService printer = context.getBean (OutPutService.class);
/ / use the object
(printer.outPut);
}
}

if you use the Java configuration using the @Scope metadata, annotations can be.


package shangbo.spring.example8;
Import org.springframework.context.annotation.Bean;
Import org.springframework.context.annotation.Configuration;
Import org.springframework.context.annotation.Scope;
@Configuration
Public class {AppConfig
@Bean
@Scope (value = "prototype")
Public OutPutService (outPutService) {
Return new (OutPutService);
}
}

- more see: Spring Framework
extract
- statement: please indicate the source

Last Updated - on 2017-05-21

Written by ShangBo on 2017-05-21

- End

Latest