SpringFramework|@Required的使用

@Required的使用

前述

Java: 1.8java

Maven: 3spring

SpringFramework版本以及各組件成員: 5.1.1.RELEASEui

  • spring-context
  • spring-core
  • spring-beans

@Required註釋適用於bean屬性setter方法, 再經過在bean定義或經過自動裝配一個明確的屬性值:this

Required意爲"須要", 它代表受影響的 bean 屬性在配置時必須放在 XML 配置文件中,不然容器就會拋出一個 BeanInitializationException 異常。code

public class SimpleMovieLister {

    private MovieFinder movieFinder;

    @Required
    public void setMovieFinder(MovieFinder movieFinder) {
        this.movieFinder = movieFinder;
    }

    // ...
}

@Required將在之後的版本棄用.xml

示例

TestBean.java - 一個Bean(這不是一個規範的JavaBean, 順口而叫的):blog

package noioo;


import org.springframework.beans.factory.annotation.Required;

public class TestBean {

    private String theValue;

    public String getTheValue() {
        return theValue;
    }

    @Required  // 用在set上面
    public void setTheValue(String theValue) {
        this.theValue = theValue;
    }
}

spring-beans.xml中啓用註解.get

<?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:content="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">

    <content:annotation-config/>

    <bean id="testBean" class="noioo.TestBean">
        <property name="theValue" value="Hello, World"/>
    </bean>
</beans>

執行者 - Runner.javait

package noioo;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Runner {

    public static void main(String[] args){
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-beans.xml");
        TestBean testBean = (TestBean)context.getBean("testBean");
        System.out.println(testBean.getTheValue());
    }
}

執行結果io

Hello, World

Process finished with exit code 0
相關文章
相關標籤/搜索