springboot--Scope注解下的bean的作用域:单态与非单态

博客围绕bean展开,涉及bean的创建、配置类、测试类及访问结果。指出非单态bean每次返回新实例,单态bean每次返回同一实例。还说明在单态bean里注入非单态bean时,单态bean维护的非单态bean实例不会被刷新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 bean的创建

package com.zfh.demo.bean;

public class ScopeBean {

	private String id;
	
	
	
	public String getId() {
		return id;
	}



	public void setId(String id) {
		this.id = id;
	}



	public ScopeBean(String id) {
		this.id = id;
	}
}

2 配置类

package com.zfh.demo.config;

import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RestController;

import com.zfh.demo.bean.ScopeBean;

@RestController
public class ScopeConfig {

	@Bean
	@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
	public ScopeBean scopeBean1() {
		return new ScopeBean("scope111");
	}
	
	
	@Bean
	@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)
	public ScopeBean scopeBean2() {
		return new ScopeBean("scope222");
	}
	
	
}

3 测试类与访问结果

package com.zfh.demo;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class SpringbootSbt04Application {

	public static void main(String[] args) {
		SpringApplication.run(SpringbootSbt04Application.class, args);
	}
	
	@Autowired
	ApplicationContext ctx;

	@GetMapping("/hello")
	public String hello() {
		System.out.println("单态的bean:"+ctx.getBean("scopeBean2"));
		System.out.println("非单态的bean:"+ctx.getBean("scopeBean1"));
		return "hello,please see console...";
	}
	
	
	
	
}

4 多刷新几次,查看结果如下

单态的bean:com.zfh.demo.bean.ScopeBean**@7fb6ce28**
非单态的bean:com.zfh.demo.bean.ScopeBean@7b895506
单态的bean:com.zfh.demo.bean.ScopeBean**@7fb6ce28**
非单态的bean:com.zfh.demo.bean.ScopeBean@5f6553f3
单态的bean:com.zfh.demo.bean.ScopeBean**@7fb6ce28**
非单态的bean:com.zfh.demo.bean.ScopeBean@2e83e342

非单态的bean每一次返回的是一个新的实例
而单态的bean每次返回的是同一个实例
那么,如果在一个单态的bean里面注入一个非单态的bean,则这个单态bean所维护的非单态bean实例,将不会被刷新。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值