代码改变世界

Spring常用配置 Scope

2016-07-17 00:08  faunjoe88  阅读(305)  评论(0编辑  收藏  举报

Bean的Scope

    Scope描述的是Spring容器如何新建Bean的实例的。Spring的Scope有以下几种,通过@Scope注解来实现。
    1.Singleton:一个Spring容器中有一个Bean的实例,此为Spring的默认配置,全容器共享一个实例。
    2.Prototype: 每次调用新建一个Bean的实例。

实例

编写Singleton的Bean

package com.wisely.highlight_spring4.ch2.scope;

import org.springframework.stereotype.Service;

@Service //1
public class DemoSingletonService {

}



代码解释
默认为Singleton,相当于@Scope("singleton")

编写Prototype的Bean
package com.wisely.highlight_spring4.ch2.scope;

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

@Service
@Scope("prototype")//1
public class DemoPrototypeService {

}

代码解释
声明Scope为Prototype

配置类
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 {

}


运行

package com.wisely.highlight_spring4.ch2.scope;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {

public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(ScopeConfig.class);
DemoSingletonService s1 = context.getBean(DemoSingletonService.class);
DemoSingletonService s2 = context.getBean(DemoSingletonService.class);

DemoPrototypeService p1 = context.getBean(DemoPrototypeService.class);
DemoPrototypeService p2 = context.getBean(DemoPrototypeService.class);

System.out.println("s1与s2是否相等"+s1.equals(s2));
System.out.println("p1与p2是否相等"+p1.equals(p2));

context.close();
}
}