SpringBoot获取Bean的工具类

 


1、beanName

  • 默认是类名首字母小写
    下面的类:beanName = bean1
@Component
public class Bean1 {
public String getBean1() {
return "Bean1";
}
}
  • 修改beanName
    下面的类:beanName = bean2New
@Component("bean2New")
public class Bean2 {
public String getBean2() {
return "Bean2";
}
}

2、工具类

package com.cc.eed.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
/**
* <p>获取spring的bean的工具类</p>
*
* @author CC
* @since 2023/10/12
*/
@Component
public class SpringBeanUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringBeanUtil.applicationContext = applicationContext;
}
/** <p>根据类的clazz获取<p>
* @param clazz clazz
* @return {@link T}
* @since 2023/10/12
* @author CC
**/
public static <T> T getBean(Class<T> clazz) {
T t = applicationContext != null ? applicationContext.getBean(clazz) : null;
Assert.notNull(t, "当前Bean为空,请重新选择!");
return t;
}
/** <p>根据Bean名字获取<p>
* @param clazzName bean名字
* @return {@link Object}
* @since 2023/10/12
* @author CC
**/
public static Object getBean(String clazzName) {
return applicationContext.getBean(clazzName);
}
}

3、使用

@Test
public void test01()throws Exception{
//方式一:根据类的clazz获取
Bean1 bean = SpringBeanUtil.getBean(Bean1.class);
System.out.println(bean.getBean1());
Bean2 bean2 = SpringBeanUtil.getBean(Bean2.class);
System.out.println(bean2.getBean2());
//方式二:根据bean名字获取
Bean1 bean11 = (Bean1) SpringBeanUtil.getBean("bean1");
System.out.println(bean11.getBean1());
//报错:NoSuchBeanDefinitionException
Bean2 bean22 = (Bean2) SpringBeanUtil.getBean("bean2");
//正确
Bean2 bean222 = (Bean2) SpringBeanUtil.getBean("bean2New");
System.out.println(bean222.getBean2());
}

posted on   C_C_菜园  阅读(789)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示