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的全部内容,希望文章能夠幫你解決所遇到的問題。
如果覺得真正的電腦專家網站内容還不錯,歡迎将真正的電腦專家推薦給好友。
有話要說...