First, the purpose
Write a project, multiple modules, and then want to implement a fixed config injection in a module, when the B module refers to a, you can directly fill in the corresponding configuration information on the line. However, when a problem is encountered, B refers to a when the configuration information of a is not always populated, and the information that is configured in B is not available. Reason for guessing: bean files for the purpose of the item are not managed uniformly.
Second, Applicationcontextaware interface
Spring provides the Applicationcontextaware class, through which you can get all the bean contexts.
That is, when a class implements this interface, the class can easily get all the beans in the ApplicationContext.
In other words, this class can get directly from the spring configuration file, all the bean objects that are referenced to.
Third, interface reference
1. Tool class Springcontextutil implement Applicationcontextaware method, realize Setapplicationcontext method can
Public classSpringcontextutilImplementsApplicationcontextaware {Private StaticApplicationContext ApplicationContext;//Spring Application Context Environment@Override Public voidSetapplicationcontext (ApplicationContext ApplicationContext)throwsbeansexception {springcontextutil.applicationcontext=ApplicationContext; } /*** Get the object * *@paramname *@returnObject An instance of the bean registered with the given name *@throwsbeansexception*/ Public StaticObject Getbean (String name)throwsbeansexception {returnApplicationcontext.getbean (name); }}
2. Business Calls
Public throws IOException { = (myconfig) springcontextutil.getcontext (). Getbean ("Myconfig"); System.out.println ("My config is" +myconfig.tostring ()); return myconfig.tostring ();}
3.MyConfig
Just a configuration map of normal properties.
How to manually get the beans in spring (Spring Applicationcontextaware get context)