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

Pri*_*mal 4 java spring spring-boot

我需要将以下 bean 自动装配到 a 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;
Run Code Online (Sandbox Code Playgroud)

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

Dav*_*ave 5

所述文档Order,包括行:

另一方面,Spring 容器内的排序策略通常基于 Ordered 接口,以便允许以编程方式配置每个实例的排序。

所以,如果你能实现的Ordered接口 ,以及在你的Slaves,这是很容易实现的。

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

使Slave接口扩展Ordered

import org.springframework.core.Ordered;

public interface Slave extends Ordered {
}
Run Code Online (Sandbox Code Playgroud)

然后让您的各个从站实现该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;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在application.properties

slave1.order=1
slave2.order=2
Run Code Online (Sandbox Code Playgroud)