Spring通过new出来的对象中带有@Autowired属性值为空的问题及解决方法

问题描述

在我new出来类对象时,发现如果该对象使用了@Autowired注入,则new出来的对象含有@Autowired的属性则为空指针。

原因解答

首先,通过使用关键字new出来的不在被spring容器管理,自然带有@Autowired属性不能被Spring容器所注入。

问题解答

如果想获取对象,可以有两种方法:

  1. 通过@Autowired动态注入你想生成的对象,这样spring容器将管理该对象。
  2. 还是通过new来生成对象,但是该对象的属性不能使用@Autowired,而是使用下面代码手动注入。那么如何手动注入呢?

下面不得不提以个接口ApplicationContextAware ,它通过Spring容器会自动把上下文环境对象调用ApplicationContextAware接口中setApplicationContext方法。我们在ApplicationContextAware的实现类中,就可以通过这个上下文环境对象得到Spring容器中的Bean。

一看到Aware就知道是干什么的了,就是属性注入的,但是这个ApplicationContextAware的不同地方在于,实现了这个接口的bean,当spring容器初始化的时候,会自动的将ApplicationContext注入进来,代码实现如下:

package com.boss.springboot.learning.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author huanghao
 * @version 1.0
 * @date 2020/3/3 11:15
 * @description 动态加载bean
 */
@Component
public class SpringContextUtil  implements ApplicationContextAware {
    //     Spring应用上下文环境
    private static ApplicationContext applicationContext;

    /**
     * 实现ApplicationContextAware接口的回调方法,设置上下文环境
     *
     * @param applicationContext
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        SpringContextUtil.applicationContext = applicationContext;
    }

    /**
     * @return ApplicationContext
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 获取对象
     * 这里重写了bean方法,起主要作用
     * @param name
     * @return Object 一个以所给名字注册的bean的实例
     * @throws BeansException
     */
    public static Object getBean(String name) throws BeansException {
        return applicationContext.getBean(name);
    }
    public static <T> T getBean(Class<T> requiredType) {

        return applicationContext.getBean(requiredType);
    }
}

 

这样我们就可以把对象含有@Autowired的注解,替换成如下形式

//手动注入
private  JavaMailSender mailSender = SpringContextUtil.getBean(JavaMailSender.class);

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值