Get the Spring container

The first: 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);   //获取接口的所有实现类

The second: 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);

The third method 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 {

}

NonAppConfig fourth method (combined third)

@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());
    }
}

The fifth startup class

@SpringBootApplication
public class MainApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(MainApplication.class, args);
    }
}
Published 172 original articles · won praise 0 · Views 5693

Guess you like

Origin blog.csdn.net/weixin_44635157/article/details/104673554