欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring Boot中獲取IOC容器的多種方式

 更新時(shí)間:2025年09月22日 11:13:24   作者:生無(wú)謂  
本文主要介紹了Spring Boot中獲取IOC容器的多種方式,包括直接注入、實(shí)現(xiàn)ApplicationContextAware接口、通過(guò)SpringApplication.run()、借助BeanFactory及實(shí)現(xiàn)BeanFactoryAware接口,感興趣的可以了解一下

1. 直接注入ApplicationContext

@Service
public class MyService {
    
    @Autowired
    private ApplicationContext applicationContext;
    
    public void doSomething() {
        // 通過(guò)ApplicationContext獲取Bean
        UserService userService = applicationContext.getBean(UserService.class);
        // 或者通過(guò)名稱獲取
        UserService userService2 = (UserService) applicationContext.getBean("userService");
    }
}

2. 實(shí)現(xiàn)ApplicationContextAware接口

@Component
public class SpringContextUtil implements ApplicationContextAware {
    
    private static ApplicationContext applicationContext;
    
    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        applicationContext = context;
    }
    
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
    
    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }
    
    public static <T> T getBean(String name, Class<T> clazz) {
        return applicationContext.getBean(name, clazz);
    }
    
    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }
}

3. 通過(guò)SpringApplication.run()獲取ApplicationContext

@SpringBootApplication
public class Application {
    
    public static void main(String[] args) {
        // 啟動(dòng)應(yīng)用并獲取ApplicationContext
        ApplicationContext context = SpringApplication.run(Application.class, args);
        
        // 直接從context中獲取Bean
        UserService userService = context.getBean(UserService.class);
        userService.doSomething();
    }
}

4. 通過(guò)BeanFactory獲取

@Service
public class MyService {
    
    @Autowired
    private BeanFactory beanFactory;
    
    public void doSomething() {
        if (beanFactory.containsBean("userService")) {
            UserService userService = (UserService) beanFactory.getBean("userService");
            // 使用userService
        }
    }
}

5. 通過(guò)實(shí)現(xiàn)BeanFactoryAware接口

@Component
public class MyComponent implements BeanFactoryAware {
    
    private BeanFactory beanFactory;
    
    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }
    
    public void doSomething() {
        UserService userService = (UserService) beanFactory.getBean("userService");
        // 使用Bean
    }
}

到此這篇關(guān)于Spring Boot中獲取IOC容器的多種方式的文章就介紹到這了,更多相關(guān)SpringBoot 獲取IOC容器內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論