Spring基於註解@Required配置
阿新 • • 發佈:2020-04-26
基於註解的配置
從 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:[email protected] 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的依賴包
&n