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());
}
标签:applicationContext,SpringBoot,getBean,获取,Bean,Bean2,Bean1,SpringBeanUtil,public
From: https://www.cnblogs.com/kakarotto-chen/p/17760069.html