2017-06-30 43 views

回答

1

您可以使用ConfigurableEnvironment組件將自定義屬性添加到現有環境。

通常,當應用程序通過偵聽ContextRefreshedEvent完全初始化時可以做到這一點,因此在那一刻可以從數據庫中檢索某些內容並與環境合併。

但是你可以將它綁定到你自己的生命週期。

這是一個簡單的例子。

說這是你的數據庫屬性定義:

@Entity 
@Table(name = "database_properties") 
public static class DatabaseProperty extends AbstractPersistable<String> { 
    private String name; 
    private String value; 

    public DatabaseProperty() {} 

    public DatabaseProperty(String name, String value) { 
     this.name = name; 
     this.value = value; 
    } 

    public String getName() { return name; } 
    public String getValue() { return value; } 
} 

隨着庫/道:

interface DatabasePropertyRepository extends JpaRepository<So44850695Application.DatabaseProperty, String> {} 

這是你如何可以與現有的環境進行合併:

@Component 
public static class PropertyEnvironment implements ApplicationListener<ContextRefreshedEvent> { 
    private final ConfigurableEnvironment configurableEnvironment; 
    private final DatabasePropertyRepository propertiesRepository; 

    @Autowired 
    public PropertyEnvironment(ConfigurableEnvironment configurableEnvironment, 
      DatabasePropertyRepository propertiesRepository) { 
     this.configurableEnvironment = configurableEnvironment; 
     this.propertiesRepository = propertiesRepository; 
    } 

    @Override 
    public void onApplicationEvent(ContextRefreshedEvent event) { 
     final Map<String, Object> properties = propertiesRepository.findAll().stream() 
       .collect(Collectors.toMap(DatabaseProperty::getName, DatabaseProperty::getValue)); 
     configurableEnvironment.getPropertySources().addLast(new MapPropertySource("db", properties)); 
    } 
} 

我相信這是最簡單的方法。

相關問題