1

I need to read my db to load a custom setting inside my Spring @Configuration class.

I have something like:

 @Configuration
    public MyConfigClass implements ApplicationContextAware{

    @Bean(initMethod = "start", destroyMethod = "stop")
    public ServerSession serverSession() throws Exception {
          ServerSession serverSession = new ServerSession(urlGateway, useSsl, hostGateway, portGateway);
      return serverSession;
    }

I should read parameters from DB instead from property file. I know that I can't @Inject my repository directly into this class, but there is a trick or something that permit me to do this or at least make a query on db?

I'm using Hibernate + Spring + Spring Data.

drenda
  • 5,846
  • 11
  • 68
  • 141

2 Answers2

2

I prefer injecting the necessary dependencies as a parameter. Using @Autowired in a field looks unnatural to me in a @Configuration class (just using stateful fields, as configuration is supposed to be stateless). Just provide it as a parameter for the bean method:

@Bean(initMethod = "start", destroyMethod = "stop")
public ServerSession serverSession(MyRepo repo) throws Exception {
    repo.loadSomeValues();
    ServerSession serverSession = new ServerSession(urlGateway, useSsl, hostGateway, portGateway);
    return serverSession;
}

This might require using @Autowired itself at method level, depending on the Spring version:

@Bean(initMethod = "start", destroyMethod = "stop")
@Autowired
public ServerSession serverSession(MyRepo repo) throws Exception {
    repo.loadSomeValues();
    ServerSession serverSession = new ServerSession(urlGateway, useSsl, hostGateway, portGateway);
    return serverSession;
}

See also:

Community
  • 1
  • 1
Aritz
  • 30,971
  • 16
  • 136
  • 217
0

Autowiring and DI work in @Configuration classes. If you're experiencing difficulties then it may be because you're trying to use the injected instance too early in the app startup lifecycle.

@Configuration
public MyConfigClass implements ApplicationContextAware{
    @Autowired
    private MyRepository repo;

    @Bean(initMethod = "start", destroyMethod = "stop")
    public ServerSession serverSession() throws Exception {
        // You should be able to use the repo here
        ConfigEntity cfg = repo.findByXXX();

        ServerSession serverSession = new ServerSession(cfg.getUrlGateway(), cfg.getUseSsl(), cfg.getHostGateway(), cfg.getPortGateway());
        return serverSession;
    }
}

public interface MyRepository extends CrudRepository<ConfigEntity, Long> {
}
pards
  • 1,098
  • 15
  • 20