当我尝试运行 Spring Boot 项目时,它告诉我它无法 Autowiring 一些在配置类中实例化的 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;
...
Controller 类:
@RestController
@RequestMapping
public class MyController{
@Autowired
private MyService service;
....
最佳答案
这意味着您没有 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;
...
}
原则上,Spring 分几个阶段执行 bean 设置,如章节 1.3.2. Instantiating Beans 中所述。文档:
Bean 定义发现 - 类似
@Configuration
的资源类(class)或XML
扫描文件并收集 Bean 签名。Eager beans 实例化,例如单例 - 来自第 1 点中收集的定义,同时解决定义之间的依赖关系。这就是为什么没有明确的 bean 实例化顺序,因为该过程是由依赖项驱动的。
Lazy beans 实例化,例如
@Lazy
带注释 - 当上下文已经启动时,只有从代码访问时才会构造此 bean。
关于spring - 为什么spring boot不按顺序加载bean配置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53254191/