SpringBoot中applicationContext对象获取及使用

本文介绍如何在Spring框架中实现依赖注入,通过示例展示了Person接口的实现类StudentPerson和TeacherPerson如何被Spring管理并调用其eat方法。利用SpringContextUtils工具类,可在运行时动态获取并调用这些bean。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需求举例:比如我们有两个人,StudentPerson和TeacherPerson,他们实现了person的eat方法,现在要根据前台的请求分别调用各自的eat方法。

public interface Person{
   void eat();
}
@Component("student")
public class StudentPerson implements Person{
   public void eat(){
      .....
   }
}

@Component("teacher")
public class TeacherPerson implements Person{
   public void eat(){
      ......
   }
}

 

SpringContext工具类

@Component
public class SpringContextUtils implements ApplicationContextAware {
   public static ApplicationContext applicationContext;

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

   public static Object getBean(String name) {
      return applicationContext.getBean(name);
   }

   public static <T> T getBean(String name, Class<T> requiredType) {
      return applicationContext.getBean(name, requiredType);
   }

   public static boolean containsBean(String name) {
      return applicationContext.containsBean(name);
   }

   public static boolean isSingleton(String name) {
      return applicationContext.isSingleton(name);
   }

   public static Class<? extends Object> getType(String name) {
      return applicationContext.getType(name);
   }

}

 测试调用

@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("dev")
public class FutureTest {
@Test
public void test(){
    String beanName = "student";
    Person person = (Person)SpringContextUtils.getBean(beanName);
    person.eat();
}
}

这里要注意SpringContextUtils类上的@Component注解是不可以去掉的,去掉后Spring就不会自动调用setApplicationContext方法来为我们设置上下文实例

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值