搜索网上的各种解决方法,使用过配置类中添加以下注解,调用时使用@Autowired注入等三四种方法,读取结果一直是null.

@Component

@ConfigurationProperties(prefix="myProps")


@Autowired  
private MyProps myProps; 

请教朋友后使用另一种方法,获取配置文件属性值成功。

实体类,

使用@DependsOn("springContextHolder")要解决使用该类静态方法时,在此之前 SpringContextHolder 类已加载!
@Configuration
@DependsOn("springContextHolder")
public class PersonConfig {

    @Value("${person.secret}")
    private String secret;

    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }
}

获取具体属性值时:

 /**
     * 配置文件
     */
private PersonConfig courierInfoConfig = SpringContextHolder.getBean(PersonConfig.class);

System.out.println("配置文件:  "+ courierInfoConfig.getSecret());

SpringContextHolder工具类

import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

/**
 * 以静态变量保存Spring ApplicationContext, 可在任何代码任何处所任何时辰中取出ApplicaitonContext
 */
@Service
@Lazy(false)
public class SpringContextHolder implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    /**
     * 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量.
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextHolder.applicationContext = applicationContext;

    }

    /**
     * 从静态变量ApplicationContext中取得Bean, 主动转型为所赋值对象的类型
     * org.springframework.beans.factory.BeanFactory.getBean(String)
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        checkApplicationContext();
        return (T) applicationContext.getBean(name);
    }

    /**
     * 从静态变量ApplicationContext中取得Bean, 主动转型为所赋值对象的类型. 若是有多个Bean合适Class, 取出第一个.
     * org.springframework.beans.factory.BeanFactory.getBean(Class<T>)
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(Class<T> clazz) {
        checkApplicationContext();
        Map beanMaps = applicationContext.getBeansOfType(clazz);
        if (beanMaps != null && !beanMaps.isEmpty()) {
            return (T) beanMaps.values().iterator().next();
        } else {
            return null;
        }
    }

    private static void checkApplicationContext() {
        if (applicationContext == null) {
            throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder");
        }
    }
}

并且yml配置文件格式要检查正常,maven要引入

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

最后这个问题就解决了,配置文件数据读取正常。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐