2016-08-12 51 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

相关问题