本例简单演示默认的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();
}
}
运行结果: