The bean in the spring container is persisted to an instance by default
Here to do a test, the base code
PackageCn.cutter.start.provider;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.support.ClassPathXmlApplicationContext;Importorg.springframework.stereotype.Component; @Component (Value= "Fxnewsprovider") Public classFxnewsprovider {//A variable is used to monitor whether the values between 2 object beans are consistent to confirm whether an object Private inttestspring; PublicFxnewsprovider () {System.out.println ("Hello IOC"); ++testspring; } Public Static voidMain (string[] args) {ApplicationContext ctx=NewClasspathxmlapplicationcontext ("Configuration file path"); Fxnewsprovider Fxnewsprovider= (Fxnewsprovider) ctx.getbean ("Fxnewsprovider"); } Public intgettestspring () {returntestspring; } Public voidSettestspring (inttestspring) { This. testspring =testspring; } }
Test Case:
@Test Public voidtest2 () {//to test spring's IOC container, the default is to keep only one instance of the IOC containerApplicationContext CTX =NewClasspathxmlapplicationcontext ("Classpath:application-bean.xml"); Fxnewsprovider Fxnewsprovider= (Fxnewsprovider) ctx.getbean ("Fxnewsprovider"); System.out.println ("Get value First:" +fxnewsprovider.gettestspring ()); Fxnewsprovider FxNewsProvider2= (Fxnewsprovider) ctx.getbean ("Fxnewsprovider"); System.out.println ("Second Fetch value:" +fxnewsprovider2.gettestspring ()); Fxnewsprovider2.settestspring (998); if(FxNewsProvider2 = =Fxnewsprovider) {System.out.println ("Two times objects, the value is:" +fxnewsprovider.gettestspring ()); } Else{System.out.println (fxnewsprovider.gettestspring ()); System.out.println (Fxnewsprovider2.gettestspring ()); } }
Finally, let's take a look at the test results
As expected in the book ...
"Sping Revelation" 3, the bean in the spring container is the default is to keep an instance