In the way that spring is based on XML configuration metadata, the bean element that is located within the property element or CONTRUCTOR-ARG element is called an internal bean, as follows:
<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.0.xsd "> <BeanID= "Outerbean"class="..."> < Propertyname= "Target"> <BeanID= "Innerbean"class="..."/> </ Property> </Bean></Beans>
The Outerbean dependency target in the XML configuration file above is injected using an internal bean. But in practical applications it is not recommended to use internal
Beans, which should be detrimental to code reuse in this way, are generally referenced using the ref attribute. Here's an example:
1. Create the package Com.tutorialspoint.inner_bean and new Texteditor.java and Spellchecker.java in the package. The contents are as follows:
Texteditor.java
Package Com.tutorialspoint.inner_bean; Public class texteditor { private spellchecker spellchecker; Public void Setspellchecker (spellchecker spellchecker) { System.out.println ("Inside setspellchecker.") ); this. spellchecker = spellchecker; } Public void spellcheck () { spellchecker.checkspelling (); }}
Spellchecker.java
Package Com.tutorialspoint.inner_bean; Public class spellchecker { public spellchecker () { System.out.println ("Inside spellchecker constructor. " ); } Public void checkspelling () { System.out.println ("Inside checkspelling.") ); }}
2. In the SRC directory, create a new inner_bean.xml configuration file with the following content:
<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.0.xsd "> <!--The following example injects an spellchecker dependency by using an internal bean - <BeanID= "TextEditor"class= "Com.tutorialspoint.inner_bean." TextEditor "> < Propertyname= "Spellchecker"> <BeanID= "Spellchecker"class= "Com.tutorialspoint.inner_bean." Spellchecker "/> </ Property> </Bean></Beans>
3. Create a new Mainapp.java in the Com.tutorialspoint.inner_bean package as follows:
PackageCom.tutorialspoint.inner_bean;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.support.ClassPathXmlApplicationContext; Public classMainapp { Public Static voidMain (string[] args) {ApplicationContext context=NewClasspathxmlapplicationcontext ("Inner_bean.xml"); TextEditor te= (TextEditor) context.getbean ("TextEditor"); Te.spellcheck (); }}
4. Run the program and check the results:
[Translate]13-spring internal bean