Spring Bean的作用域之prototype

Spring中Bean的默认最用域是单例,即singleton
prototype是只在每次getBean的时候都去重新创建一个对象。下面我们来掩饰一下这种场景
使用SpringBoot项目。创建两个Controller一个service和一个实现类

@Controller
public class HomeController1 {
    @Autowired
   TestService testService;
//    @Lookup
//    public TestService getTestService(){
//        return  null;
//    }
    @RequestMapping("test1")
    public  String test(){
        System.out.println(testService.hashCode());
        return "test";
    }
}
@Controller
public class HomeController2 {
    @Autowired
    TestService testService;
    @RequestMapping("test2")
    public  String test(){
        System.out.println(testService.hashCode());
        return "test";
    }
}
public interface TestService {
    public  void  say();
}

@Service
//@Scope("prototype")
public class TestServiceImpl  implements TestService{
    @Override
    public void say() {
        System.out.println("hahhahah");
    }
}

当注释掉@Scope注解时我们分别访问localhost:8080/test1可见hashcode的打印都是一样的。当我们放开@Scope注解的注释之后。分别访问localhost:8080/test1和localhost:8080/test2可以看到hashcode是不一样的。但是我们看到多次访问localhost:8080/test1时hashcode是一样的,因为这个时候获取Bean是同一次获取的。

题外话

   @Lookup
    public TestService getTestService(){
       return  null;
    }

这个可以代替AutoWired自动注入

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值