码迷,mamicode.com
首页 > 编程语言 > 详细

Spring常用配置 Scope

时间:2016-07-17 13:13:36      阅读:293      评论:0      收藏: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();
}
}


技术分享




 

Spring常用配置 Scope

标签:

原文地址:http://www.cnblogs.com/faunjoe88/p/5677585.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!