Populating a spring bean using a constructor-arg field

后端 未结 2 1081
小蘑菇
小蘑菇 2021-02-02 11:59

How can i inject a properties file containing a Map to be used as additional constructor arg using the field.

With a Map being loaded from a properties file

the

2条回答
  •  再見小時候
    2021-02-02 12:41

    Create a bean that loads the properties (and takes the file name as an argument) and inject that instead.

    EDIT When using annotations, things like constructor injection become more simple:

    @Bean
    public Map configuration() {
        return EmbeddedGraphDatabase.loadConfigurations( "neo4j_config.props" );
    }
    
    @Bean
    public GraphDatabaseService graphDb() {
        return new EmbeddedGraphDatabase( "data/neo4j-db", configuration() );
    }
    

    Note that the second bean definition method "simply" calls the first. When this code is executed, Spring will do some magic so you can still override the bean elsewhere (i.e. beans still overwrite each other) and it will make sure that the method body will be executed only once (no matter how often and from where it was called).

    If the config is in a different @Configuration class, then you can @Autowired it:

    @Autowired
    private Map configuration;
    
    @Bean
    public GraphDatabaseService graphDb() {
        return new EmbeddedGraphDatabase( "data/neo4j-db", configuration );
    }
    

提交回复
热议问题