@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方法上( 2.@Required作用在Setter方法上就必须赋值,否则容器就会抛出一个 BeanInitializationException 异常。 |
1.@Autowired 可以作用在Setter 方法中,属性,构造函数中2.可以使用 @Autowired 的 (required=false) 选项关闭默认行为。也就是被标注的属性不会被赋值 |
联系 | 1.@Required作用在Setter方法上需要生成Setter方法 | 1.@Autowired 作用在Setter 方法也需要生成Setter方法 2.@Autowired 作用在属性上,则可以省略Setter方法,根据Bean类型来注入 |