基于Springboot使用@Autowired注解获取实例和Java工具类获取实例

基于Springboot使用@Autowired注解获取实例和Java工具类获取实例

1. @Autowired的使用及获取实例
@Autowired是获取bean实例的注解,与其搭配使用的注解有@Component、@Repository、@Service、@Controller、@RestController等。
@Autowired获取的是spring容器中装载的对象,如:

 @Autowired
 private UserService userService;

那么问题来了,很多时候我们写的一些类中没有使用与@Autowired注解相关的其他注解时,却又想获取到spring中装载的实例。那么怎么办?
(1)如果依然使用@Autowired注解的方式行吗?答案是不行,这样获取的是空,程序运行过程中会出现NullPointerExceprion。
(2)如果使用new关键字创建的当时行吗?答案是也不行,因为new创建的对象是没有被装载到spring中的。

那么可以通过Java工具类获取我们需要的bean。废话少说上代码。

3. 使用Java工具类获取实例和装载实例(实现ApplicationContextAware 的方式获取bean)

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
 
/**
 * @describe:  获取springcontext中的bean
 */
@Component
public class SpringContextUtil implements ApplicationContextAware {
    
    public static ApplicationContext context;
 
    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        SpringContextUtil.context = context;
    }
    
    /**
     * 获取容器中的实例
     * @param beanId 注入在Spring容器中的bean的ID 默认为类名首字母小写
     * @param clazz 获取的bean的实际的类的class   
     */
    public static <T> T getBean(String beanId, Class<T> clazz){
        return context.getBean(beanId, clazz);
    }
 
    public static ApplicationContext getContext(){
        return context;
    }
}

值得注意的是:这里的getBean(String beanId, Class<T> class)就是下面SpringMvc中的配置bean的代码

<bean id="" class="" />

调用举例,如下:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陌守

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值