[英]Instantiate beans in order in Spring?
是否可以在Spring中設置實例化順序?
我不想使用@DependsOn
而且我不想使用Ordered
接口。 我只需要一個實例化的命令。
@Order
注釋的以下用法不起作用:
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
/**
* Order does not work here
*/
public class OrderingOfInstantiation {
public static class MyBean1 {{
System.out.println(getClass().getSimpleName());
}}
public static class MyBean2 {{
System.out.println(getClass().getSimpleName());
}}
@Configuration
public static class Config {
@Bean
@Order(2)
public MyBean1 bean1() {
return new MyBean1();
}
@Bean
@Order(1)
public MyBean2 bean2() {
return new MyBean2();
}
}
public static void main(String[] args) {
new AnnotationConfigApplicationContext(Config.class);
}
}
Bean仍按字典順序實例化。
為什么它在這里不起作用?
我還能依靠詞典順序嗎?
UPDATE
我想任何允許提供創作順序的解決方案。
目標是以正確的順序在配置級別填充集合。 Depends on
- 與任務不匹配。 關於為什么Spring不喜歡有序實例化的任何“解釋” - 也與該任務不匹配。
訂單意味着訂單:)
來自@Order
javadoc
注意: 僅對特定類型的組件支持基於注釋的排序 - 例如,對於基於注釋的AspectJ方面。 另一方面,Spring容器中的排序策略通常基於Ordered接口,以便允許以編程方式配置每個實例的順序。
所以我猜Spring在創建bean時並不遵循@Order()
。
但是如果你只想填充集合,也許這對你來說已經足夠了:
import com.google.common.collect.Multimap;
import com.google.common.collect.MultimapBuilder;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import java.lang.annotation.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@Configuration
public class OrderingOfInstantiation {
public static void main(String[] args) {
new AnnotationConfigApplicationContext(OrderingOfInstantiation.class);
}
@Component
@CollectionOrder(collection = "myBeans", order = 1)
public static class MyBean1 {{
System.out.println(getClass().getSimpleName());
}}
@Component
@CollectionOrder(collection = "myBeans", order = 2)
public static class MyBean2 {{
System.out.println(getClass().getSimpleName());
}}
@Configuration
public static class CollectionsConfig {
@Bean
List<Object> myBeans() {
return new ArrayList<>();
}
}
// PopulateConfig will populate all collections beans
@Configuration
public static class PopulateConfig implements ApplicationContextAware {
@SuppressWarnings("unchecked")
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
Multimap<String, Object> beansMap = MultimapBuilder.hashKeys().arrayListValues().build();
// get all beans
applicationContext.getBeansWithAnnotation(CollectionOrder.class)
.values().stream()
// get CollectionOrder annotation
.map(bean -> Pair.of(bean, bean.getClass().getAnnotation(CollectionOrder.class)))
// sort by order
.sorted((p1, p2) -> p1.getRight().order() - p2.getRight().order())
// add to multimap
.forEach(pair -> beansMap.put(pair.getRight().collection(), pair.getLeft()));
// and add beans to collections
beansMap.asMap().entrySet().forEach(entry -> {
Collection collection = applicationContext.getBean(entry.getKey(), Collection.class);
collection.addAll(entry.getValue());
// debug
System.out.println(entry.getKey() + ":");
collection.stream()
.map(bean -> bean.getClass().getSimpleName())
.forEach(System.out::println);
});
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
public @interface CollectionOrder {
int order() default 0;
String collection();
}
}
它不會改變實例化順序,但是你會獲得有序的集合。
如果要確保在另一個bean之前創建特定bean,可以使用@DependsOn批注。
@Configuration
public class Configuration {
@Bean
public Foo foo() {
...
}
@Bean
@DependsOn("foo")
public Bar bar() {
...
}
}
請記住,這不會設置順序,它只保證在“bar”之前創建bean“foo”。 @DependsOn的JavaDoc
您可以通過首先消除類MyBean1
和MyBean2
上的靜態來強加您的示例中的排序,在幾乎每種情況下都不需要使用Spring,因為Spring的默認設置是實例化每個bean的單個實例(類似於Singleton) 。
訣竅是將MyBean1
和MyBean2
聲明為@Bean
並強制執行順序,通過從bean1的初始化方法中調用bean2的bean初始化方法,創建從bean1到bean2的隱式依賴項。
例如:
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
/**
* Order does not work here
*/
public class OrderingOfInstantiation {
interface MyBean{
default String printSimpleName(){
System.out.println(getClass().getSimpleName());
}
}
public class MyBean1 implments MyBean{
public MyBean1(){ pintSimpleName(); }
}
public class MyBean2 implments MyBean{
public MyBean2(){ pintSimpleName(); }
}
public class MyBean3 implments MyBean{
public MyBean3(){ pintSimpleName(); }
}
public class MyBean4 implments MyBean{
public MyBean4(){ pintSimpleName(); }
}
public class MyBean5 implments MyBean{
public MyBean5(){ pintSimpleName(); }
}
@Configuration
public class Config {
@Bean
MyBean1 bean1() {
//This will cause a a dependency on bean2
//forcing it to be created before bean1
bean2();
return addToAllBeans(new MyBean1());
}
@Bean
MyBean2 bean2() {
//This will cause a a dependency on bean3
//forcing it to be created before bean2
bean3();
//Note: This is added just to explain another point
//Calling the bean3() method a second time will not create
//Another instance of MyBean3. Spring only creates 1 by default
//And will instead look up the existing bean2 and return that.
bean3();
return addToAllBeans(new MyBean2());
}
@Bean
MyBean3 bean3(){ return addToAllBeans(new MyBean3()); }
@Bean
MyBean4 bean4(){ return addToAllBeans(new MyBean4()); }
@Bean
MyBean5 bean5(){ return addToAllBeans(new MyBean5()); }
/** If you want each bean to add itself to the allBeans list **/
@Bean
List<MyBean> allBeans(){
return new ArrayList<MyBean>();
}
private <T extends MyBean> T addToAllBeans(T aBean){
allBeans().add(aBean);
return aBean;
}
}
public static void main(String[] args) {
new AnnotationConfigApplicationContext(Config.class);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.