基於注解的配置
從 Spring 2.5 開始就可以使用注解來配置依賴注入。而不是采用 XML 來描述一個 bean 連線,你可以使用相關類,方法或字段聲明的注解,將 bean 配置移動到組件類本身。
在 XML 注入之前進行注解注入,因此后者的配置將通過兩種方式的屬性連線被前者重寫。
注解連線在默認情況下在 Spring 容器中不打開。因此,在可以使用基於注解的連線之前,我們將需要在我們的 Spring 配置文件中啟用它。所以如果你想在 Spring 應用程序中使用的任何注解,可以考慮到下面的配置文件。
1 <?xml version="1.0" encoding="UTF-8"?> 2 3 <beans xmlns="http://www.springframework.org/schema/beans" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xmlns:context="http://www.springframework.org/schema/context" 6 xsi:schemaLocation="http://www.springframework.org/schema/beans 7 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 8 http://www.springframework.org/schema/context 9 http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 10 11 <context:annotation-config/> 12 <!-- bean definitions go here --> 13 14 </beans>
@Required 注釋應用於 bean 屬性的 setter 方法,它表明受影響的 bean 屬性在配置時必須放在 XML 配置文件中,否則容器就會拋出一個 BeanInitializationException 異常。
下面顯示的是一個使用 @Required 注釋的示例
下面是 Student.java 文件的內容:
1 package com.spring.chapter5; 2 3 import java.util.List; 4 import java.util.Set; 5 6 import org.springframework.beans.factory.annotation.Required; 7 8 9 10 public class Student { 11 12 public String getName() { 13 return name; 14 } 15 @Required 16 public void setName(String name) { 17 this.name = name; 18 } 19 20 public int getAge() { 21 return age; 22 } 23 @Required 24 public void setAge(int age) { 25 this.age = age; 26 } 27 private String name; 28 private int age; 29 30 31 32 }
下面是 MainApp.java 文件的內容:
1 package com.spring.chapter5; 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 @Required 注解注入 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 Student student=(Student)applicationContext.getBean("student"); 21 System.out.println("名字是:"+student.getName()); 22 System.out.println("年齡是:"+student.getAge()); 23 24 25 } 26 27 }
下面是配置文件 Beans.xml: 文件的內容: 上面的頭信息就省略了
<!-- @Required 注解 --> <bean id="student" class="com.spring.chapter5.Student"> <property name="name" value="張三"></property> <!-- age屬性 --> <!-- <property name="age" value="24"></property> --> </bean>
@Required 注釋應用於 bean 屬性的 setter 方法,它表明受影響的 bean 屬性在配置時必須放在 XML 配置文件中,否則容器就會拋出一個 BeanInitializationException 異常。下面顯示的是一個使用 @Required 注釋的示例,當中setAge()方法標注了當中age的屬性配置被注銷了。所以會報 BeanInitializationException 異常。在生產規模的應用程序中,IoC容器中可能會有數百或數千個bean,並且它們之間的依賴關系通常非常復雜。setter注入的一個缺點是你很難檢查是否已經設置了所有必需的屬性
運行結果:
名字是:張三
年齡是:24
注意:在使用@Required注解注入時,我們需要添加spring-aop的依賴包