我需要将以下 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/