Spring 单例模式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/oumingyuan/article/details/82557111

单例模式(Singleton Pattern)

单例模式简介

singleton: 表示在spring容器中的单例,通过spring容器获得该bean时总是返回唯一的实例
prototype:表示每次获得bean都会生成一个新的对象

@Service
//@Scope("prototype")
@Scope("singleton")//如果不写,默认是 单例模式
public class DemoSingletonServiceImpl {

    public void say() {

    }
}
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoSingletonServiceImplTest {

    @Autowired
    DemoSingletonServiceImpl DemoSingletonServiceImpl1;

    @Autowired
    DemoSingletonServiceImpl DemoSingletonServiceImpl2;

    @Test
    public void say() {

        System.out.println(DemoSingletonServiceImpl1 == DemoSingletonServiceImpl2);//true

    }

}

猜你喜欢

转载自blog.csdn.net/oumingyuan/article/details/82557111