SpringBoot配置多例实例

一般springIOC容器取出的bean是SINGLETON单例
但是如果需要生成多例Bean怎么配置




前言

这里需要用到SpringBoot配置类,Test方法,测试POJO


提示:以下是本篇文章正文内容,下面案例可供参考

一、测试POJO

public class Dode {
    private int id;
    private Dode nextdode;

    public Dode getNextdode() {
        return nextdode;
    }

    public void setNextdode(Dode nextdode) {
        this.nextdode = nextdode;
    }

    public Dode() {
    }

    public int getId() {
        return id;
    }

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

这里@Data省去了getset方法和tostring
@Scope里面参数表示注入多例

二、配置类

代码如下(示例):

@RestController
public class pojoconfig {

    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)

    public Dode mkdode(){
        return new Dode();
    }
}

测试类

代码如下(示例):

@SpringBootTest
class DemoApplicationTests {

    @Autowired
    ApplicationContext applicationContext;

    @Test
    void contextLoads() {

        Dode head = (Dode) applicationContext.getBean("mkdode");
        Dode next = (Dode) applicationContext.getBean("mkdode");
        Dode dode3 = (Dode) applicationContext.getBean("mkdode");
        Dode dode4 = (Dode) applicationContext.getBean("mkdode");
        Dode pre = (Dode) applicationContext.getBean("mkdode");

        System.out.println(head);
        System.out.println(next);
        System.out.println(dode3);
com.ldz.demo.POJO.Dode@4da9f723
com.ldz.demo.POJO.Dode@3b2f4a93
com.ldz.demo.POJO.Dode@213bd3d5

代理方法获取Bean

@RestController
@Configuration(proxyBeanMethods = false)
public class pojoconfig {

    @Bean
//    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)

    public Dode mkdode(){
        return new Dode();
    }
}

被@Configuration注解的配置类被springCG接管的代理类,选项proxyBeanMethods = true的时候,spring会实时检查,配置类里面的bean是否在容器中存在,如果存在就调用容器里的组件所以,代理类创造的bean是同一个Bean
如果@Configuration(proxyBeanMethods = false)
被标注的配置类就不是代理对象
多次调用生成Bean方法,生成的Bean不是同一个Bean

  pojoconfig pojoconfig = applicationContext.getBean(pojoconfig.class);
        Dode dode1 = pojoconfig.mkdode();
        Dode dode2 = pojoconfig.mkdode();
		    System.out.println(dode1==dode2);

false

总结

这样的方法会得到不同的dode实例

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐