Spring中Bean的Scope

本例简单演示默认的Singleton和Prototype,分别从Spring容器中获取2次Bean,判断Bean的实例是否相等

(1)编写Singleton的bean

package com.zawl.erp.portal.test;

import org.springframework.stereotype.Service;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>公司: </p>
 * @autho andy
 * @time 2019年8月1日 下午11:38:59
*/
@Service
public class DemoSingleService {

}

Spring中默认为Singleton,相当于@Scope("singleton")

(2)编写Prototype的bean

package com.zawl.erp.portal.test;

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

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>公司: </p>
 * @autho andy
 * @time 2019年8月1日 下午11:38:59
*/
@Service
@Scope("prototype")
public class DemoProtoTypeService {

}

 

(3)配置类

package com.zawl.erp.portal.test;

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

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>公司: </p>
 * @autho andy
 * @time 2019年8月1日 下午11:37:41
*/
@Configuration
@ComponentScan("com.zawl.erp.portal.test")
public class ScopeConfig {

}

注意:配置类中声明的@ComponentScan中的路径应该包含锁声明的测试bean,否侧无法扫描到具体的bean

 

(4)运行

package com.zawl.erp.portal.service.bizservice;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.zawl.erp.portal.test.DemoProtoTypeService;
import com.zawl.erp.portal.test.DemoSingleService;
import com.zawl.erp.portal.test.ScopeConfig;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>公司: </p>
 * @autho andy
 * @time 2019年8月1日 下午11:40:57
*/
public class Main {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ScopeConfig.class);
		System.out.println("容器初始化成功");
		DemoSingleService s1 = context.getBean(DemoSingleService.class);
		DemoSingleService s2 = context.getBean(DemoSingleService.class);
		DemoProtoTypeService p1 = context.getBean(DemoProtoTypeService.class);
		DemoProtoTypeService p2 = context.getBean(DemoProtoTypeService.class);
		System.out.println(s1==s2);
		System.out.println(p1==p2);
		context.close();
	}
}

运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值