springboot 通過類名稱獲取bean


IOC容器有beanFactory 和ApplicationContext.通常建議使用后者,因為它包含了前者的功能。Spring的核心是ApplicationContext.它負責管理 beans 的完整生命周期。我們可以從applicationContext里通過bean名稱獲取安裝的bean.進行某種操作。不能直接使用applicationContext.而需要借助applicationContextAware.具體方法如下:

@Component
public class ApplicationContextGetBeanHelper implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public static Object getBean(String className) throws BeansException,IllegalArgumentException {
        if(className==null || className.length()<=0) {
            throw new IllegalArgumentException("className為空");
        }

        String beanName = null;
        if(className.length() > 1) {
            beanName = className.substring(0, 1).toLowerCase() + className.substring(1);
        } else {
            beanName = className.toLowerCase();
        }
        return applicationContext != null ? applicationContext.getBean(beanName) : null;
    }

}

聲明一個ApplicationContextHelper組件,名字隨意。它實現了ApplicationContextAware接口。並重寫setApplicationContext方法。在該組件里可以通過名字獲取某個bean.

 

 

使用

@Slf4j
@RestController
@RequestMapping("/getbean")
public class GetBeanTestController {

    @GetMapping("/retryService")
    public String retryService(@RequestParam int num){

        RetryService retryService = (RetryService) ApplicationContextGetBeanHelper.getBean("RetryService");
        String ss = retryService.print();

        return ss;
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM