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实例,将不会被刷新。