Spring常用配置(1) --- Bean的Scope

1、Bean的Scope

1.1、理论

Scope描述的是Spring容器如何新建Bean的实例,可以通过@Scope注解实现

  • Singleton:默认配置,一个Spring容器中只有一个Bean的实例,全容器共享一个实例。
  • Prototype:每次调用新建一个Bean实例。
  • Request:Web项目中,给每一个http request 新建一个Bean实例。
  • Session:Web项目中,给每一个http session新建一个Bean实例。
  • GlobalSession:这个旨在protal应用中有用,给每一个global http session 新建一个Bean实例。

    2.1、示例

    1)编写Singleton的Bean
package com.wisely.highlight_spring4.ch2.scope;

import org.springframework.stereotype.Service;

@Service 
//@Scope("singleton")
public class DemoSingletonService {

}

2)编写Prototype的Bean

package com.wisely.highlight_spring4.ch2.scope;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

@Service
@Scope("prototype")//声明多例
public class DemoPrototypeService {

}

3)配置类

package com.wisely.highlight_spring4.ch2.scope;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.wisely.highlight_spring4.ch2.scope")
public class ScopeConfig {

}

猜你喜欢

转载自www.cnblogs.com/bigfly277/p/9476263.html