2017-08-25 82 views
1

如果在初始化過程中沒有完全配置我的Bean,我希望Spring Boot引發異常。我認爲這樣做的正確方法是用@Required註釋相關Bean方法,但它不像我預期的那樣工作。@Required即使在初始化bean時也會導致異常

application.yml:

my_field: 100 

簡單bean類:

package com.example.demo; 

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

@Component 
public class MyProperties { 
    private int myField; 

    public MyProperties(){} 

    @Required 
    public void setMyField(int myField) { 
     this.myField = myField; 
    } 

    @Override 
    public String toString() { 
     return "{myField=" + myField + '}'; 
    } 
} 

我的應用程序類:

package com.example.demo; 

import org.springframework.boot.SpringApplication; 
import org.springframework.boot.autoconfigure.SpringBootApplication; 
import org.springframework.boot.context.properties.ConfigurationProperties; 
import org.springframework.context.annotation.Bean; 

import javax.annotation.PostConstruct; 

@SpringBootApplication 
public class DemoApplication { 

    @Bean 
    @ConfigurationProperties 
    public MyProperties getMyProperties() { 
     return new MyProperties(); 
    } 

    @PostConstruct 
    public void init() { 
     MyProperties myProperties = getMyProperties(); 
     System.out.println(myProperties); 
    } 

    public static void main(String[] args) { 
     SpringApplication.run(DemoApplication.class, args); 
    } 
} 

在DemoApplication的init方法,我打印生成的bean對象。如果沒有@Required註釋,它會正確加載並打印{myField=100}。但是,當我添加註釋時,它會引發此異常:

org.springframework.beans.factory.BeanInitializationException: Property 'myField' is required for bean 'myProperties' 

儘管配置文件包含所需值,

什麼是正確的告訴春,一個字段是必需的?

回答

0

docs

春天開機時會嘗試驗證@ConfigurationProperties班時,他們與Spring的@Validated註解。您可以直接在配置類上使用JSR-303 javax.validation約束註釋。只要確保符合JSR-303實現你的類路徑,然後添加約束註釋到你的領域

你應該申報myField如下:

@NonNull 
private int myField;