简体   繁体   中英

How do I add a JPA based PropertySource to external configuration in Spring boot

I've been trying to add a custom PropertySource to the spring Environment bean but cannot get it to work. I have a Spring boot application and have managed to do the following

@Bean
public Environment environment() {
    ConfigurableEnvironment environment = new StandardServletEnvironment();
    MutablePropertySources propertySources = environment.getPropertySources();  
    propertySources.addFirst(new DatabasePropertySource("databaseProperties"));
    return environment;
}

public class DatabasePropertySource extends PropertySource<DatabaseReaderDelegate> {

    public DatabasePropertySource(String name) {
        super(name, new DatabaseReaderDelegate());
    }

    @Override
    public Object getProperty(String name) {
        return this.source.getProperty(name);
    }
}

public class DatabaseReaderDelegate {

    @Autowired ConfigurationDao dao;

    public Object getProperty(String property) {
        Configuration object = dao.findOneByConfKey(property);
        Object value = object.getConfValue();
        return value;
    }
}

public interface ConfigurationDao extends JpaRepository<Configuration, Long> {
    Configuration findOneByConfKey(String name);
}

This definitely adds a DatabasePropertySource to the StandardServletEnvironment but there isn't any data as the ConfigurationDao that is @Autowired is null. I have wired in the ConfigurationDao elsewhere and it does work and data is accessible through it. I just think it is a matter of timing during startup but I'm not sure exactly how to order/time it. Has anyone done something similar and have any help to offer to make this happen.

Getting JPA to start up in time to include it in the Environment is probably impossible (it's chicken and egg). One way to break the cycle is to initialize your database and repository in a parent context, and then use it in the Environment of the child (your main application context). There are convenience methods for building parent and child contexts in SpringApplicationBuilder .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM