SpringContextHolder直接从spring容器中获取bean

SpringContextHolder直接从spring容器中获取bean

创建类 SpringContextHolder

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
 
@Component
public class SpringContextHelper implements ApplicationContextAware {
    private static ApplicationContext applicationContext;
 
    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        SpringContextHelper.applicationContext = applicationContext;
    }
 
    public static ApplicationContext getApplicationContext(){
        return applicationContext;
    }
 
    public static Object getBean(String name){
        return applicationContext.getBean(name);
    }
    /**
     * 从spring 上下文中获取bean
     * @param name
     * @param requiredClass
     * @return
     */
    public static <t> T getBean(String name, Class<t>  requiredClass){
        return applicationContext.getBean(name, requiredClass);
    }
    public  static <t> T getBean(Class<t> requiredType){
        return applicationContext.getBean(requiredType);
    }
 
}

使用示例 : 

  MyService myService= SpringContextHolder.getBean(MyService.class);
  String s=myService.hello("张三");
 System.out.println(s);

MyService 是托管自spring容器中的bean 。在任意对象的方法代码中都可以使用SpringContextHolder类的静态方法获取spring容器中的bean .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot,可以通过@Autowired注解来从Spring容器获取对象。首先,确保你的类被Spring容器管理,可以使用@Component或者@Service等注解进行标记。然后,在需要获取对象的地方,使用@Autowired注解将对象注入进来。这样,Spring Boot会自动从容器找到对应的对象并注入到你的类。例如,假设你想获取名为"beanId"的对象,你可以在需要使用该对象的地方使用@Autowired注解进行注入,如下所示: @Autowired private BeanType bean; 其BeanType是你要获取对象的类型,bean是你给该对象起的变量名。这样,Spring Boot会自动将名为"beanId"的对象注入到bean变量,你就可以在类使用该对象了。 #### 引用[.reference_title] - *1* [spring boot获取spring容器bean对象](https://blog.csdn.net/qq_29235677/article/details/119652555)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [Spring Boot获取通过@Bean注入Spring容器对象实体](https://blog.csdn.net/weixin_42146366/article/details/102633076)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值