If the bean on which a bean depends does not want to be directly accessed by the spring container, you can useNested Bean.<Bean.../>Elements are used to define nested beans. nested beans are only valid for external beans that are nested in them. Spring containers cannot directly access nested beans. Therefore, you do not need to specify the ID attribute when defining nested beans:
Axe. Java:
public interface Axe {public String chop();}
Person. Java:
public interface Person {public void useAxe();}
Chinese. Java:
public class Chinese implements Person{private Axe axe;public void setAxe(Axe axe) {this.axe = axe;}@Overridepublic void useAxe() {System.out.println(axe.chop());}}
Steelaxe. Java:
Public class steelaxe implements axe {@ overridepublic string chop () {return "cutting firewood well ";}}
Bean. XML Core Configuration:
<bean id="chinese" class="com.bean.Chinese"> <property name="axe"> <bean class="com.bean.SteelAxe"/> </property></bean>
The preceding configuration ensures that the nested bean cannot be accessed by containers. Therefore, you do not need to worry about modifying the nested bean by other programs. The external bean usage is exactly the same as the previous usage.
Nested beans limit bean access and improve the cohesion of the program.
UseNested BeanAnd useRefThe reference of another bean in the container is essentially the same. In fact, to inject attributes to bean instances, when the attribute type is a composite type, a Java object needs to be passed in, so there are two ways:
① Use ref to reference the bean (Java object) configured in a container ).
② Use bean to temporarily configure a nested Bean (Java object ).
Test. Java:
Public class test {public static void main (string [] ARGs) {applicationcontext CTX = new classpathxmlapplicationcontext ("bean. XML "); person P = (person) CTX. getbean ("Chinese"); p. useaxe (); // cut firewood with a steel axe }}