Spring Boot中获取IOC容器的方式

57 阅读1分钟

1. 直接注入ApplicationContext

@Service
public class MyService {
    
    @Autowired
    private ApplicationContext applicationContext;
    
    public void doSomething() {
        // 通过ApplicationContext获取Bean
        UserService userService = applicationContext.getBean(UserService.class);
        // 或者通过名称获取
        UserService userService2 = (UserService) applicationContext.getBean("userService");
    }
}

2. 实现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. 通过SpringApplication.run()获取ApplicationContext

@SpringBootApplication
public class Application {
    
    public static void main(String[] args) {
        // 启动应用并获取ApplicationContext
        ApplicationContext context = SpringApplication.run(Application.class, args);
        
        // 直接从context中获取Bean
        UserService userService = context.getBean(UserService.class);
        userService.doSomething();
    }
}

4. 通过BeanFactory获取

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

5. 通过实现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
    }
}