In the previous example,ProgramBean objects are always obtained by bean ID.
However, in reality, the relationship between a bean and bean is managed through dependency injection, and bean instances are often not obtained by calling the getbean method of the container. It is possible that the application has obtained a reference from the bean instance, but the program cannot know the ID attribute specified when the bean is configured, the program needs to specify the ID attribute When configuring the bean.
In some extreme cases, you need to obtain the ID attribute specified when deploying the bean in the container when developing bean classes. In this case, you can use
BeannameawareInterface that allows the Bean class to obtain the ID attribute specified when the bean is deployed.
The beannameaware interface provides the following methods:Setbeanname (string name)The name parameter of this method is the bean ID. The Bean class implementing this method can obtain the ID of the bean to be deployed through this method.
Chinese. Java:
Public class Chinese implements beannameaware {private string beanname; @ overridepublic void setbeanname (string name) {This. beanname = Name;} public void getbeanid () {system. out. println ("Chinese implementation class, the ID specified when the bean is deployed is:" + beanname );}}
Bean. xmlCore Configuration:
<Bean id = "Chinese" class = "com. Bean. Chinese"/>
Test. Java:
Public class test {public static void main (string [] ARGs) {applicationcontext CTX = new classpathxmlapplicationcontext ("bean. XML "); Chinese c = (Chinese) CTX. getbean ("Chinese"); C. getbeanid ();}}
Run test. Java and the console outputs:
When will the spring container call back the setbeanname (string name) method of the bean instance? Spring containers call back this method after Bean Initialization is complete ------ the initialization here refersBean Initialization:The callback includes the afterpropertiesset method implemented by the initializingbean interface and the method specified by the init-method attribute in the callback bean configuration. After the spring container completes bean initialization, it will call back the setbeanname (string
Name) method.