Obtenez le conteneur Spring

La première: 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);   //获取接口的所有实现类

La seconde: 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);

La troisième méthode 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 quatrième méthode (de troisième combiné)

@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 cinquième classe de démarrage

@SpringBootApplication
public class MainApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(MainApplication.class, args);
    }
}
Publié 172 articles originaux · louanges gagnées 0 · Vues 5693

Je suppose que tu aimes

Origine blog.csdn.net/weixin_44635157/article/details/104673554
conseillé
Classement