Spring Boot-在IOC容器中将Bean创建为Singleton

问题描述 投票:0回答:2

Bean的创建应该是在春季容器中的Singleton,对吗?我正在将带有注释的Spring配置文件迁移到Spring Boot。我有以下代码,但每次在另一个bean创建中使用它时,它似乎都会调用“ mySingletonBean()”。据我了解,@ Bean注释默认情况下应为Singleton。我是否正确创建我的Bean?

@Bean
public SomeBean mySingletonBean() {
  SomeBean mybean = new SomeBean();
  mybean.setName = "Name";
  return mybean;
}

@Bean 
public Bean1 bean1() {
  Bean1 bean1 = new Bean1();
  bean1.setBean(mySingletonBean());
  return bean1;
}

@Bean 
public Bean2 bean2() {
  Bean2 bean2 = new Bean2();
  bean2.setBean(mySingletonBean());
  return bean2;
}


java spring spring-boot ioc-container
2个回答
0
投票

Spring正在代理您的应用程序上下文类,并负责所有与上下文相关的事情,例如实例化,缓存bean等。

运行此小测试,请随时调试以查看配置类成为什么类:

package stackoverflow;

import java.util.Arrays;
import java.util.Date;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static org.junit.Assert.assertTrue;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Test.MyContext.class)
public class Test {

    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    @Qualifier("myStringBean")
    private String myStringBean;
    @Autowired
    private SomeBean someBean;

    @Configuration
    static class MyContext {

        @Bean
        public String myStringBean() {
            return String.valueOf(new Date().getTime());
        }

        @Bean
        public SomeBean mySomeBean() {
            return new SomeBean(myStringBean());
        }

    }

    @org.junit.Test
    public void test() {
        assertTrue(myStringBean == applicationContext.getBean("myStringBean"));
        assertTrue(myStringBean == someBean.getValue());
        System.out.println(Arrays.asList(applicationContext.getBean("myStringBean"), myStringBean, someBean.getValue()));
    }

    static class SomeBean {

        private String value;

        public SomeBean(String value) {
            this.value = value;
        }

        public String getValue() {
            return value;
        }
    }

}

-1
投票

Spring Boot是一个智能框架,方法mySingletonBean()仅会启动一次,不用担心。您可以启动调试模式,然后查看。

© www.soinside.com 2019 - 2024. All rights reserved.