java - Spring 和@Value 注解

标签 java spring

我正在尝试使用 Spring 框架构建控制台应用程序。

我有一个由@SpringBootApplication注释的类:

@SpringBootApplication
public class LoaderApplication {

    public static void main(String[] args) {
        SpringApplication.run(LoaderApplication.class, args);
    }
}

以及被@Component注解的类

@Component
public class ElasticLoader implements CommandLineRunner {

    // Elastic properties
    @Value("${elasticTransportAddress:#{null}}")
    private String elasticTransportAddress;

    private static final Logger log = LoggerFactory.getLogger(ElasticLoader.class);

    @Override
    public void run(String... arg) throws Exception {
        if (!( elasticTransportAddress != null && elasticTransportAddress.isEmpty() )) {
            log.error("[elasticTransportAddress] is not defined in property file");
            return;
        }
        log.info("-> ElasticLoader.run");
    }
}

如您所见,在这个类中,我尝试通过 @Value 注释注入(inject)属性 elasticTransportAddress 值,但是在运行我的应用程序后,我可以看到该属性 elasticTransportAddress 保持未分配状态。

我错过了什么?

让我添加一些注释:

我想将我的应用程序与不同的属性文件一起使用。对于这种情况,我创建了包含以下内容的 xml-context-config.xml:

    <beans profile="companies">
    <!-- allows for ${} replacement in the spring xml configuration from the
        application-default.properties, application-dev files on the classpath -->
    <context:property-placeholder
            location="classpath:companies.properties"
            ignore-unresolvable="true" />

    <!-- scans for annotated classes in the com.env.dev package -->
    <context:component-scan base-package="ru.alexeyzhulin" />
</beans>

并使用我放在

中的配置文件companies.properties

enter image description here

我的运行配置与描述的配置文件:

enter image description here

并且此配置文件已启用,正如我在应用程序日志中看到的那样:

2017-01-15 00:10:39.697  INFO 10120 --- [           main] ru.alexeyzhulin.LoaderApplication        : The following profiles are active: companies

但是当我在 application.properties 中定义属性并使用默认配置文件时,属性 elasticTransportAddress 被分配。

最佳答案

将 companies.properties 重命名为 application-companies.properties。 Link到文档

关于java - Spring 和@Value 注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41653357/

相关文章:

java - JUnit:具有私有(private)字段的测试生成器

java - 如何计算多个字符串中某个字符出现的次数?

java - Spark : createDataset() into a Dataset<Row>?

java - org.springframework.beans.factory.UnsatisfiedDependencyException : Error creating bean with name.无法让我的springboot应用程序运行

带有键,值类型消息的spring cloud stream SOURCE

java - 字符串资源 XML 文件是否允许无效的 Java 变量作为名称属性?

java - Spring Boot变量/嵌套请求体

java - Spring DSL : Sending error message to JMS queue. 获取错误 'one-way ' MessageHandler' 并且不适合配置 'outputChannel' '

spring - Dart MIME类型在 Spring 之前更改为vnd.dart

java - 如何验证十进制输入不允许单独 "."和空字段?