获取spring容器中的实例

梦里梦外; 2022-12-09 01:54 202阅读 0赞

获取spring容器中的实例

  1. @Component
  2. public class ApplicationContextProvider implements ApplicationContextAware {
  3. /** * 上下文对象实例 */
  4. private static ApplicationContext applicationContext;
  5. @Override
  6. public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
  7. this.applicationContext = applicationContext;
  8. }
  9. /** * 获取applicationContext * * @return */
  10. public static ApplicationContext getApplicationContext() {
  11. return applicationContext;
  12. }
  13. /** * 通过name获取 Bean. * * @param name * @return */
  14. public Object getBean(String name) {
  15. return getApplicationContext().getBean(name);
  16. }
  17. /** * 通过class获取Bean. * * @param clazz * @param <T> * @return */
  18. public <T> T getBean(Class<T> clazz) {
  19. return getApplicationContext().getBean(clazz);
  20. }
  21. /** * 通过name,以及Clazz返回指定的Bean * * @param name * @param clazz * @param <T> * @return */
  22. public <T> T getBean(String name, Class<T> clazz) {
  23. return getApplicationContext().getBean(name, clazz);
  24. }
  25. }

该类必须得让spring能够扫描到

发表评论

表情:
评论列表 (有 0 条评论,202人围观)

还没有评论,来说两句吧...

相关阅读