java - 属性和环境始终为空

标签 java spring

我很难从我的属性文件中加载属性。我正在尝试将属性加载到下面列出的配置类中。

package dk.fitfit.budget.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.Environment;


@Configuration
@PropertySource("classpath:application.properties")
public class ApplicationConfig {
    private static final Logger logger = LoggerFactory.getLogger(ApplicationConfig.class);

    @Autowired
    private Environment env;

    @Value("${snot:test}")
    private String snot;

    public ApplicationConfig() {
        logger.info("Application config loaded!");  // Displays as expected
        logger.info("snot: {}", snot);              // snot: null
        logger.info("env: {}", env);                // env: null
    }

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

}

如果我更改文件名 (application.properties) 或“@PropertySource("classpath:application.properties")”,我会收到有关文件不存在的错误消息。很明显它正在加载(无论如何在某种程度上)。

我至少希望看到默认字符串“test”被注入(inject)到变量 snot 中。但甚至还没有完成。我也无法 Autowiring 环境...不确定是否存在关系。

我的application.properties的内容如下。

snot=snog

我的application.properties文件放在src/main/resources/。

有人知道我做错了什么吗?

最佳答案

构造函数的目的是初始化类实例。在 Spring 可以对其执行任何操作之前,您必须构造和初始化类实例。因此,您不能期望 envsnot 字段在构造函数中具有除默认 null 值以外的任何值。

关于java - 属性和环境始终为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26455936/

相关文章:

java - 使用 DB 和社交网站登录

java - 从 Excel 导入空日期

java - 如何实例化和填充 Page<Object[]>

Java Guice - 像 Spring 一样创建多个 'beans' 的 guice 等效方法?

java - 在 Spring Boot 中使用 @TestPropertySource 覆盖 @PropertySource

java - 表格 :errors not displaying errors on JSP in Spring

java - 测试 JPA 实体

java - 如何在 Java 中重写库方法?

java - 将客户端注册到服务器 - java 套接字编程

java - Spring Data JPA 获取具有连接表的实体的方法