Spring定義bean的三種方式和自動注入


一、定義bean的三種途徑:        

  • 首先編寫Student和Teacher兩個類
  • public class Student {  
      
        private String name;  
      
        private Teacher teacher;  
      
        public String getName() {  
            return name;  
        }  
      
        public void setName(String name) {  
            this.name = name;  
        }  
      
        public Teacher getTeacher() {  
            return teacher;  
        }  
      
        public void setTeacher(Teacher teacher) {  
            this.teacher = teacher;  
        }  
      
    }  
    public class Teacher {  
      
        private String name;  
      
        public String getName() {  
            return name;  
        }  
      
        public void setName(String name) {  
            this.name = name;  
        }  
      
    }  

     

    • 方法一:基於XML的bean定義(需要提供setter方法)
    • <?xml version="1.0" encoding="UTF-8"?>  
      <beans xmlns="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.xsd">  
        
          <bean id="student" class="test.Student">  
              <property name="name" value="張三"/>  
              <property name="teacher" ref="teacher"/>  
          </bean>  
        
          <bean id="teacher" class="test.Teacher">  
              <property name="name" value="李四"/>  
          </bean>  
        
      </beans>  
      [java] view plain copy
      public class Main {  
        
          public static void main(String args[]){  
              FileSystemXmlApplicationContext context=new FileSystemXmlApplicationContext("applicationContext.xml的絕對路徑");  
              Student student= (Student) context.getBean("student");  
              Teacher teacher= (Teacher) context.getBean("teacher");  
              System.out.println("學生的姓名:"+student.getName()+"。老師是"+student.getTeacher().getName());  
              System.out.println("老師的姓名:"+teacher.getName());  
          }  
        
      }  
      • 方法二:基於注解的bean定義(不需要提供setter方法)
      Spring為此提供了四個注解,這些注解的作用與上面的XML定義bean效果一致,在於將組件交給Spring容器管理。組件的名稱默認是類名(首字母變小寫),也可以自己修改:
      @Component:當對組件的層次難以定位的時候使用這個注解
      @Controller:表示控制層的組件
      @Service:表示業務邏輯層的組件
      @Repository:表示數據訪問層的組件
      使用這些注解的時候還有一個地方需要注意,就是需要在applicationContext.xml中聲明<contex:component-scan...>一項,指明Spring容器掃描組件的包目錄。
    • @Component("teacher")  
      public class Teacher {  
        
          @Value("李四")  
          private String name;  
        
          public String getName() {  
              return name;  
          }  
        
      }  
      [java] view plain copy
      @Component("student")  
      public class Student {  
        
          @Value("張三")  
          private String name;  
        
          @Resource  
          private Teacher teacher;  
        
          public String getName() {  
              return name;  
          }  
        
          public Teacher getTeacher() {  
              return teacher;  
          }  
        
      }  
      [html] view plain copy
      <?xml version="1.0" encoding="UTF-8"?>  
      <beans xmlns="http://www.springframework.org/schema/beans"  
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
             xmlns:context="http://www.springframework.org/schema/context"  
             xsi:schemaLocation="http://www.springframework.org/schema/beans  
             http://www.springframework.org/schema/beans/spring-beans.xsd  
             http://www.springframework.org/schema/context  
             http://www.springframework.org/schema/context/spring-context.xsd">  
        
          <!--掃描組件的包目錄-->  
          <context:component-scan base-package="test"/>  
        
      </beans>  
      [java] view plain copy
      public class Main {  
        
          public static void main(String args[]){  
              FileSystemXmlApplicationContext context=new FileSystemXmlApplicationContext("applicationContext.xml的絕對路徑");  
              Student student= (Student) context.getBean("student");  
              Teacher teacher= (Teacher) context.getBean("teacher");  
              System.out.println("學生的姓名:"+student.getName()+"。老師是"+student.getTeacher().getName());  
              System.out.println("老師的姓名:"+teacher.getName());  
          }  
        
      }  

       

      • 方法三:基於Java類的bean定義(需要提供setter方法)
      • @Configuration  
        public class BeansConfiguration {  
          
            @Bean  
            public Student student(){  
                Student student=new Student();  
                student.setName("張三");  
                student.setTeacher(teacher());  
                return student;  
            }  
          
            @Bean  
            public Teacher teacher(){  
                Teacher teacher=new Teacher();  
                teacher.setName("李四");  
                return teacher;  
            }  
          
        }  
        [java] view plain copy
        public class Main {  
          
            public static void main(String args[]){  
                AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext(BeansConfiguration.class);  
                Student student= (Student) context.getBean("student");  
                Teacher teacher= (Teacher) context.getBean("teacher");  
                System.out.println("學生的姓名:"+student.getName()+"。老師是"+student.getTeacher().getName());  
                System.out.println("老師的姓名:"+teacher.getName());  
            }  
          
        }  

        二、Spring的自動注入

        • Spring提供了五種自動裝配的類型
        no:顧名思義, 顯式指明不使用Spring的自動裝配功能
        byName:根據屬性和組件的名稱匹配關系來實現bean的自動裝配
        byType:根據屬性和組件的類型匹配關系來實現bean的自動裝配,有多個適合類型的對象時裝配失敗
        constructor:與byType類似是根據類型進行自動裝配,但是要求待裝配的bean有相應的構造函數
        autodetect:利用Spring的自省機制判斷使用byType或是constructor裝配

         

        • 基於XML的自動裝配

         
        <?xml version="1.0" encoding="UTF-8"?>  
        <beans xmlns="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.xsd">  
          
            <bean id="student" class="test.Student" autowire="byName">  
                <property name="name" value="張三"/>  
            </bean>  
          
            <bean id="teacher" class="test.Teacher">  
                <property name="name" value="李四"/>  
            </bean>  
          
        </beans>  

         

        這里我並沒有顯式為Student對象注入Teacher屬性,而是使用autowired="byName"代替,這樣一來Spring會幫我們處理這些細節,將名字是teacher的組件注入到Student對象中。
         
        • 基於注解的自動裝配
        其實上面已經應用過了,這里再提一下@Resource和@Autowired的區別。@Resource默認是使用byName進行裝配,@Autowired默認使用byType進行裝配。

         
        @Component("teacher")  
        public class Teacher {  
          
            @Value("李四")  
            private String name;  
          
            public String getName() {  
                return name;  
            }  
          
            public void setName(String name) {  
                this.name = name;  
            }  
        }  
        
         
        @Component("student")  
        public class Student {  
          
            @Value("張三")  
            private String name;  
          
            @Resource  
            private Teacher teacher;  
          
            public String getName() {  
                return name;  
            }  
          
            public void setName(String name) {  
                this.name = name;  
            }  
          
            public Teacher getTeacher() {  
                return teacher;  
            }  
          
            public void setTeacher(Teacher teacher) {  
                this.teacher = teacher;  
            }  
        }  

         



        三、如何進行選擇?

          • <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">          

            <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/study"/> <property name="username" value="賬號"/> <property name="password" value="密碼"/> </bean>

             

            自動裝配:一般我使用基於注解的自動裝配。同樣也是為了減少XML配置文件的“篇幅”。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM