package com.dj.springbootdemo.config;
import com.dj.springbootdemo.service.CarService;
import com.dj.springbootdemo.service.SystemInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
/**
* User: ldj
* Date: 2023/6/4
* Time: 0:06
* Description: No Description
*/
@Slf4j
@Configuration
public class LoadBeansConfig {
/*
* 1. 我们都知道 @Order数字越小优先级越高
* 2. bean加载顺序,默认是从上往下加载,
* 3. @Order对不是同一类型的Bean的加载顺序没有作用!,没有作用! 没有作用!
* 4. @Order是控制同一个接口的实现类(Bean)加载顺序
*/
@Bean
@Order(5)
public SystemInfoService loadSystemInfoService() {
log.info("加载SystemService...");
return new SystemInfoService();
}
@Bean
@Order(0)
public CarService loadCarService(){
log.info("加载CarService...");
return new CarService();
}
}
解决1: 最简单的方式就是按照自上而下进行书写,被依赖的Service就写在上面,让它先加载成Bean
解决2: BeanFactory是遍历保存在List集合的BeanDefinition (定义态)进行生产,那你按顺序注册进去List<BeanDefinition>
/**
* User: ldj
* Date: 2023/6/3
* Time: 22:27
* Description: No Description
*/
public class MyApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
configurableApplicationContext.addBeanFactoryPostProcessor(new MyBeanFactoryPostProcessor());
}
}
package com.dj.springbootdemo.initializer;
import com.dj.springbootdemo.service.CarService;
import com.dj.springbootdemo.service.SystemInfoService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
/**
* User: ldj
* Date: 2023/6/3
* Time: 22:29
* Description: No Description
*/
public class MyBeanFactoryPostProcessor implements BeanDefinitionRegistryPostProcessor {
//将bean的定义态按照自定义的顺序放入List,这样就实现SpringBean的有序加载
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
AbstractBeanDefinition systemInfoServiceBeanDefinition = BeanDefinitionBuilder.genericBeanDefinition(SystemInfoService.class).getBeanDefinition();
AbstractBeanDefinition carServiceBeanDefinition = BeanDefinitionBuilder.genericBeanDefinition(CarService.class).getBeanDefinition();
beanDefinitionRegistry.registerBeanDefinition("systemInfoService", systemInfoServiceBeanDefinition);
beanDefinitionRegistry.registerBeanDefinition("carService", carServiceBeanDefinition);
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
}
}