一.Bean的scope
Scope描述的是Spring容器如何新建Bean的市里的。Spring的Scope有以下几种,通过
@Scope注解来实现。
(1)singleton:一个Spring容器中只有一个Bean的实例,为此Spring的默认配置,全容器
共享一个实例。
(2)Prototype:每次调用新建一个Bean的实例。
(3)Request:Web项目中,给每一个http request新建一个Bean实例。
(4)Session:Web项目中,给每一个http session新建一个Bean实例。
(5)GlobalSession:这个只在portal应用中有用,给每一个global http session新建一个
实例。
二,示例一
package scope;
import org.springframework.stereotype.Service;
@Service
public class DemosingletonService {
}
代码解释
默认为Singleton,相当于@Scope(“singleton”)。
实例二
package scope;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
@Service
@Scope("prototype")
public class DemoPrototypeService {
}
代码解释
声明Scope为Prototype。
示例三 配置类
package scope;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("scope")
public class ScopeConfig {
}
实例四 测试
package scope;
import javax.xml.ws.handler.MessageContext.Scope;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ScopeConfig.class);
DemosingletonService service1 = context.getBean(DemosingletonService.class);
DemosingletonService service2 = context.getBean(DemosingletonService.class);
DemoPrototypeService service3 = context.getBean(DemoPrototypeService.class);
DemoPrototypeService service4 = context.getBean(DemoPrototypeService.class);
DemoPrototypeService service5 = new DemoPrototypeService();
DemoPrototypeService service6 = new DemoPrototypeService();
System.out.println(service1.equals(service2));
System.out.println(service3.equals(service4));
System.out.println(service5.equals(service6));
}
}
结果
true
false
false