In spring, autowire = "byname" or "bytype" can be used to provide automatic injection. However, you must note that it does not support automatic injection of basic data types (such as string, Int, and long. For example
Java class:
- Public class testbean {
- Private string name;
- Private long age;
- Private string fullname;
- Private testbean2 testbean2;
- Public void settestbean2 (testbean2 testbean2 ){
- This. testbean2 = testbean2;
- }
- Public testbean2 gettestbean2 (){
- Return testbean2;
- }
- Public void setfullname (string fullname ){
- This. fullname = fullname;
- }
- Public String getfullname (){
- Return fullname;
- }
- Public void setage (long age ){
- This. Age = age;
- }
- Public long getage (){
- Return age;
- }
- Public void setname (string name ){
- This. Name = Name;
- }
- Public String getname (){
- Return name;
- }
- }
Java Class 2:
- Public class testbean2 {
- Public String getstring (){
- Return "testb ";
- }
- }
Configuration file:
- <Beans default-autowire = "byname">
- <! -- Login -->
- <Bean id = "testbean" class = "testbean">
- <Property name = "fullname">
- <Value> fullname </value>
- </Property>
- </Bean>
- <Bean id = "name" class = "Java. Lang. String">
- <Constructor-Arg>
- <Value> hell </value>
- </Constructor-Arg>
- </Bean>
- <Bean id = "Age" class = "Java. Lang. Long">
- <Constructor-Arg>
- <Value> 20 </value>
- </Constructor-Arg>
- </Bean>
- <Bean id = "testbean2" class = "testbean2"/>
- </Beans>
Test class:
- Import org. springframework. Context. Support. classpathxmlapplicationcontext;
- Public class test {
- Public static void main (string [] ARGs ){
- Classpathxmlapplicationcontext T = new classpathxmlapplicationcontext (
- "Test. xml ");
- Testbean bean = (testbean) T. getbean ("testbean ");
- System. Out. println ("name:" + bean. getname () + "Age:" + bean. getage ()
- + "Fullname:" + bean. getfullname () + "testbean2"
- + Bean. gettestbean2 (). getstring ());
- }
- }
The output result is:
Name: NULL age: NULL fullname: fullname testbean2: testb
To exclude the code of the basic type from spring source code (the source code is from the org. springframework. Beans. Factory. Support. abstractautowirecapablebeanfactory class), go:
- Protected string [] unsatisfiednonsimpleproperties (abstractbeandefinition mbd, beanwrapper BW ){
- Set result = new treeset ();
- Propertyvalues PVS = mbd. getpropertyvalues ();
- Propertydescriptor [] PPS = BW. getpropertydescriptors ();
- For (INT I = 0; I <PPS. length; I ++ ){
- If (PPS [I]. getwritemethod ()! = NULL &&! Isexcludedfromdependencycheck (PAM [I]) &
- ! PVS. Contains (PPS [I]. getname ())&&! Beanutils. issimpleproperty (PPS [I]. getpropertytype ())){
- Result. Add (PPS [I]. getname ());
- }
- }
- Return stringutils. tostringarray (result );
- }
Pay attention to the purple section above. The unsatisfiednonsimpleproperties method is called during Automatic injection. Therefore, basic types are not injected.