为什么Spring Boot不按顺序加载bean配置?

时间:2018-11-11 23:13:33

标签: spring spring-boot

当我尝试运行spring boot项目时,它告诉我它无法自动装配一些在配置类中实例化的bean。 我认为spring无法按顺序加载这些配置类。

堆栈跟踪:no bean found the be autowired Ignite<Long,MyEntity> myEntityCache in MyDao

以下是来源:

主要班级

@SpringBootApplication
// The beans in the IgniteConfig have to be loaded before dao, service, and Controller
@ComponentScan(basePackageClasses={IgniteConfig.class,AppConfig.class})
public class DemoIgnite {
   public static void main(String[] args) {
       SpringApplication.run(DemoIgnite .class, args);
   }
}

配置类别1

@Configuration
public class IgniteConfig {
@Bean
public SpringContext springContext() {
    return new SpringContext();
}

@Bean
public Ignite igniteInstance(@Autowired SpringContext springContext) {
IgniteConfiguration cfg = new IgniteConfiguration();
cfg.setIgniteInstanceName("instance");
List<CacheConfiguration> ccDas = new ArrayList<>();
CacheConfiguration cch = new CacheConfiguration<>("myEntitycache");
cch.setCacheMode(CacheMode.REPLICATED);
cch.setIndexedTypes(Long.class, myEntity.class);
ccDas.add(cch);
cfg.setCacheConfiguration( ccDas.toArray(new CacheConfiguration[0]));
SpringCacheManager springCacheManager = new SpringCacheManager();
springCacheManager.setConfiguration(cfg);
return Ignition.start(cfg);


}

@Bean
public IgniteCache<Long, MyEntity> myEntityCache(@Autowired Ignite igniteInstance) {
 return igniteInstance.cache("myEntitycache");
}

配置类2

@Configuration
@ComponentScan({
"com.demo.repository",
"com.demo.service",
"com.demo.controller"
})
public class AppConfig {
}

道课

@Repository
public class MyDao{

@Autowired
private Ignite<Long,MyEntity> myEntityCache;
...

服务等级:

@Service
public class MyService{

@Autowird
private MyDao dao;
...

控制器类:

@RestController
@RequestMapping
public class MyController{

@Autowired
private MyService service;
....

1 个答案:

答案 0 :(得分:1)

这意味着您在上下文中没有Ignite<Long,MyEntity>类型的Bean。而且springContext bean似乎是多余的,igniteInstance bean没有使用它。正如moilejter所指出的,它应该是:

IgniteConfig

@Bean
public Ignite ignite() {
  ...
}

@Bean
public IgniteCache<Long, MyEntity> myEntityCache() {
  return ignite().cache("myEntitycache");
}

MyDao

@Repository
public class MyDao {

  @Autowired
  private IgniteCache<Long, MyEntity> myEntityCache;

  ...
}

原则上,如1.3.2. Instantiating Beans文档中所述,Spring按几个阶段执行Bean设置:

  1. Bean定义发现-扫描@Configuration类或XML文件等资源并收集Bean签名。

  2. Eager bean实例化,例如单例-从点1收集的定义中解决定义之间的依赖关系。这就是为什么没有明确的bean实例化顺序的原因,因为该过程是由依赖关系驱动的。

  3. 惰性豆实例化@Lazy带注释-当上下文已经建立时,仅当从代码访问时,才会构造此bean。