java - 如何在 spring boot 中从属性文件为 @Order 注释设置值

标签 java spring spring-boot

我需要将以下 bean Autowiring 到 List,并且我需要对我的 List 进行排序。我就是这样做的:

@Service
@Order(1)
public class Slave1 implements Slave {}

@Service
@Order(2) //instead of hardcoding I need the value to be picked up externally
public class Slave2 implements Slave {}

@Autowire
List<Slave> slaves;

但我希望从 application.properties 文件中获取订单值。 这可能吗?我可以从属性文件中为 @Order 注释设置一个值吗?

最佳答案

documentation对于 Order,包括以下行:

Ordering strategies within the Spring container, on the other hand, are typically based on the Ordered interface in order to allow for programmatically configurable ordering of each instance.

因此,如果您能够实现 Ordered interface在您的 Slaves 中,这也很容易实现。

使用您的代码,我尝试了以下方法,这似乎有效:

使Slave接口(interface)扩展Ordered:

import org.springframework.core.Ordered;

public interface Slave extends Ordered {
}

然后让您的个人奴隶实现 getOrder() 方法,返回一个值,该值是用 @Value 设置的,取自您的 application.properties 文件:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class Slave1 implements Slave {
    @Value("${slave1.order}")
    private int myOrder;

    @Override
    public int getOrder() {
        return myOrder;
    }
}

然后在 application.properties 中:

slave1.order=1
slave2.order=2

关于java - 如何在 spring boot 中从属性文件为 @Order 注释设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45628574/

相关文章:

java - Spring 启动 hibernate 配置

spring-boot - Kubernetes 在单独的端口上使用 Spring Boot 应用程序进行事件/就绪检查

mysql - Spring 集成 : error while inseting records in database with jdbc outbound gateway

java - Jmonkey碰撞检测

java - android studio 本地化不翻译

java - Renjin 无法加载包

java - 如何使用 Hibernate/Spring/Tomcat 拦截 JDBC 查询?

java - RabbitMQ、docker、单队列、多个消费者

java - 使用构造函数注入(inject)的 spring @RestController 中的空异常 @Service

java - Cordova 不适用于 Java 9。如何仅为 Cordova 设置特定的 jdk?