Obtener el contenedor de Primavera

La primera: SpringUtil

//1.SpringUtil
@Component
public class SpringUtil extends ApplicationObjectSupport {
    public static ApplicationContext context;
    
    public static Object getBean(String serviceName){
        return context.getBean(serviceName);
    }
    
    @Override
    protected void initApplicationContext(ApplicationContext context) throws BeansException {
        super.initApplicationContext(context);
        SpringUtil.context = context;      
    }
}
//2.使用
ApplicationContext context = SpringUtil.context;  //获取Spring容器
PayServiceUtil payServiceUtil = context.getBean(PayServiceUtil.class);  //获取bean
Map<String, PayService> payMap = context.getBeansOfType(PayService.class);   //获取接口的所有实现类

El segundo: PayServiceUtil

@Component
public class PayServiceUtil implements ApplicationContextAware {
    //1.初始化Spring容器对象
    private ApplicationContext applicationContext;
    
    //2.获取Springr容器对象
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
    
   //3.使用容器对象
   Map<String, PayService> payMap = applicationContext.getBeansOfType(PayService.class);

El tercer método AppConfig

public class Test {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        DeptMapperImpl deptMapper = context.getBean(DeptMapperImpl.class);
        deptMapper.test();
    }
}

@ComponentScan("com.base")
@Configuration
public class AppConfig {

}

cuarto método NonAppConfig (tercera combinado)

@ComponentScan("com")
public class TestNoAppConfig {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainApplication.class);
        DeptService deptService = context.getBean(DeptService.class);
        deptService.delete(new Dept());
    }
}

La quinta clase de arranque

@SpringBootApplication
public class MainApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(MainApplication.class, args);
    }
}
Publicados 172 artículos originales · ganado elogios 0 · Vistas 5693

Supongo que te gusta

Origin blog.csdn.net/weixin_44635157/article/details/104673554
Recomendado
Clasificación