javaEE颠覆者四

javaEE颠覆者第二章
2.1.1 spring简单单例演示
(1)编写Singleton的bean

package spring4.scope;

import org.springframework.stereotype.Service;

@Service //什么也不做 默认为单例 Singleton 相当于@Scope("singleton")  这是Spring的默认配置(这我都忘了  大哭)
public class DemoSingletonService {

}

(2)编写Prototype的bean

package spring4.scope;

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

@Service
@Scope("prototype") //Scope("prototype") 是多例   而如果不写的话 默认为单例  Scope("singleton")
public class DemoPrototypeService {

}

(3)配置类

package spring4.scope;

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

@Configuration
@ComponentScan("spring4.scope")
public class ScopeConfig {

}

(4)运行

package spring4.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();
    }
}

结果:
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值