Spring基於 @Autowired 和@Required區別與聯系


@Autowired  可以使用在Setter 方法中,屬性,構造函數中。

例如:在屬性當中使用@Autowired,這里是 TextEditor.java 文件的內容:

 1 package com.spring.chapter6;
 2 
 3 import java.util.List;
  4 import java.util.Set;
 5 
  6 import org.springframework.beans.factory.annotation.Autowired;
  7 import org.springframework.beans.factory.annotation.Required;
 8 
  9 
 10 
 11 public class TextEditor {
 12 
 13  
 20     @Autowired
 21     private SpellChecker spellChecker;
 22     
 23     public void getSpell(){
 24         spellChecker.checkSpelling();
 25         
 26     }

 

 

下面是另一個依賴的類文件 SpellChecker.java 的內容:

 1 package com.spring.chapter6;
 2 
 3 public class SpellChecker {
 4     
 5     public SpellChecker(){
 6           System.out.println("Inside SpellChecker constructor." );
 7        }
 8        public void checkSpelling(){
 9           System.out.println("Inside checkSpelling." );
10        }  
11 
12 }

 

 

下面是 MainApp.java 文件的內容:

 1 package com.spring.chapter6;
 2 
 3 
 4 import java.util.List;
 5 
 6 import org.springframework.context.ApplicationContext;
 7 import org.springframework.context.support.AbstractApplicationContext;
 8 import org.springframework.context.support.ClassPathXmlApplicationContext;
 9 
10 public class Main {
11     /**
12      * Spring @autowired 注解注入
13      * author:
14      * mail:2536201485@qq.com
15      * 時間:
16      */
17 
18     public static void main(String[] args) {
19         ApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring_xml/spring.xml");
20         TextEditor editor=(TextEditor)applicationContext.getBean("textEditor");
21         editor.getSpell();
22         
23         
24     }
25 
26 }

 

 

下面是配置文件 spring.xml

1     <!-- @autowired 注解-->
2     <bean id="textEditor" class="com.spring.chapter6.TextEditor">
3     </bean>
4     <bean id="SpellChecker" class="com.spring.chapter6.SpellChecker">
5     </bean>

 

 

運行結果:

Inside SpellChecker constructor.
Inside checkSpelling.

 

@Required和@Autowired的區別:

  @Required

@Autowired

區別

1.@Required作用在Setter方法上(用於檢查一個Bean的屬性的值在配置期間是否被賦予或設置(populated))

2.@Required作用在Setter方法上就必須賦值,否則容器就會拋出一個 BeanInitializationException 異常。

1.@Autowired  可以作用在Setter 方法中,屬性,構造函數中

2.可以使用 @Autowired 的 (required=false) 選項關閉默認行為。也就是被標注的屬性不會被賦值

聯系 1.@Required作用在Setter方法上需要生成Setter方法

1.@Autowired 作用在Setter 方法也需要生成Setter方法

2.@Autowired 作用在屬性上,則可以省略Setter方法,根據Bean類型來注入


免責聲明!

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



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