Spring Java配置:在自动装配之前调用的重写@Bean方法

时间:2014-05-23 10:13:58

标签: spring inheritance autowired spring-java-config

RepositoryConfig延长了Neo4jConfiguration。后者使用@Bean注释方法设置了许多bean。 RepositoryConfig会覆盖在getGraphDatabaseService中的任何字段自动装配之前调用的RepositoryConfig。这是一个问题,因为我想在getGraphDatabaseService方法中使用自动装配的东西。

@ConfigurationProperties(prefix = "neo4j")
public class RepositoryProperties {
   [...]
}

@Configuration
@EnableNeo4jRepositories("com.foo.bar")
@EnableConfigurationProperties(RepositoryProperties.class)
public class RepositoryConfig extends Neo4jConfiguration {
   @Autowired
   private RepositoryProperties properties;

   @Override
   @Bean(name = "graphDatabaseService", destroyMethod = "shutdown")
   public GraphDatabaseService getGraphDatabaseService() {
      [...] // properties is 'null' at this point
   }

   @PostContstruct
   public void foo() {
      [...] // properties is initiated OK here
   }
}

为什么在自动装配完成之前调用getGraphDatabaseService?我想它与继承有关...如果我删除了继承,那么在调用getGraphDatabaseService时自动装配就完成了。我也尝试用@DependsOn注释该方法,没有运气。

非常感谢任何想法!

1 个答案:

答案 0 :(得分:0)

是的,我偶尔也看过这个。我认为有两种解决方法。

选项1.自动装配bean定义

@Override    
@Bean(name = "graphDatabaseService", destroyMethod = "shutdown")
@Autowired
public GraphDatabaseService getGraphDatabaseService() {
  [...] // properties is 'null' at this point
}

选项2.注入bean

@Override    
@Bean(name = "graphDatabaseService", destroyMethod = "shutdown")
public GraphDatabaseService getGraphDatabaseService(@Autowired RepositoryProperties properties) {
   // can probably delete the Config member with this approach
  [...] // properties is 'null' at this point
}