2016-08-12 38 views
1

我需要讀取我的數據庫以加載Spring @Configuration類中的自定義設置。將Spring庫存入Spring @Configuration類

我有類似:

@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; 
    } 

我應該從數據庫而不是從屬性文件中讀取參數。我知道我不能@直接將我的存儲庫注入到這個類中,但是有一個技巧或某些東西可以讓我這樣做,或者至少可以在db上進行查詢?

我正在使用Hibernate + Spring + Spring Data。

回答

1

我更喜歡注入必要的依賴關係作爲參數。在@Configuration類中使用@Autowired在字段中看起來不自然(僅使用有狀態字段,因爲配置應該是無狀態的)。只需提供它作爲bean的方法的參數:

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

這可能需要使用@Autowired本身在方法層面,取決於Spring版本:

@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; 
} 

參見:

+0

就像一個魅力。謝謝 – drenda

+0

不客氣;-) –

0

@Configuration類中的自動裝配和DI工作。如果您遇到困難,那可能是因爲您嘗試在應用程序啓動生命週期中過早使用注入的實例。

@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> { 
} 
+0

我還試過你寫的同樣的東西,但不幸的是回購仍然爲空。 – drenda