Bean的创建应该是spring容器中的单例,对吗?我正在将Spring配置文件迁移到带注释的Spring Boot。我有下面的代码,但它似乎每次在另一个bean创建中使用时都会调用"mySingletonBean()“。我的理解是,默认情况下,@Bean注释应该是Singleton。我是否正确地创建了我的Beans?
@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;
}
回答开始:得票数 0
Spring代理您的应用程序上下文类,并处理所有与上下文相关的事情,如beans的实例化、缓存等。
运行这个小测试,可以随意调试,看看配置类变成了什么类:
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;
}
}
}
总结
以上是真正的电脑专家为你收集整理的Spring Boot -在IOC容器中创建单例Bean的全部内容,希望文章能够帮你解决所遇到的问题。
如果觉得真正的电脑专家网站内容还不错,欢迎将真正的电脑专家推荐给好友。
有话要说...