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 getBean(Class requiredType) {

        return applicationContext.getBean(requiredType);
    }
}

 

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

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

 

你可能感兴趣的:(Spring学习)