在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML5  Java/ spring是否能在其它bean完成init之后才創(chuàng)建另外一個(gè)bean的實(shí)例?

spring是否能在其它bean完成init之后才創(chuàng)建另外一個(gè)bean的實(shí)例?

有個(gè)需要引用bean的工具類

@Component
class FooUtils implements InitializingBean {
    private static Foo foo;
    private static Bar bar;

    @Autowired
    private void foo(Foo foo) {
        MyFactory.foo = foo;
    }    

    @Override
    public void afterPropertiesSet() throws Exception {
        bar = new Bar(foo, ...);
    }
    
    public static MyObj create(int param1, int param2, int param3) {
        if (foo == null) { thrown new Exception(); }
        return new MyObj(foo.baz(param1, param2), bar, param3);
    }
}

想用上面那個(gè)工具類創(chuàng)建bean

@Configuration
@DependsOn('fooUtils') // <-- 然而不work, 開始new實(shí)例的時(shí)候都還沒進(jìn)行bean的init
class Config {
    @Bean
    public MyObj myObjBean() {
        return FooUtils.create(1, 2, 3); // <-- 想不到怎么讓這里在fooUtils完成autowired之后才執(zhí)行
    }
}
@Service
class MyService {
    @Autowired
    private MyObj myObj;
}
回答
編輯回答
淺時(shí)光

你這樣子寫相當(dāng)于建了一個(gè)Bean:fooUtils,但是你調(diào)用的是FooUtils,這兩個(gè)不是同一個(gè)實(shí)例。

如何解決。

  1. 將調(diào)用改成fooUtils
  2. 在FooUtils的create方法里面使用getBean拿到想要使用的Bean
  3. 改變實(shí)現(xiàn)工具類的思路,避免在工具類中引用Bean
2018年8月28日 10:55
編輯回答
悶騷型

改成,還不行就把create改成實(shí)例方法

    @Bean
    public MyObj myObjBean(FooUtils utils) {
        return FooUtils.create(1, 2, 3);
    }
2017年6月18日 00:11
編輯回答
久礙你

請(qǐng)看spring有關(guān)DependsOn注解的注釋,我這里列出來。


/**
 * Beans on which the current bean depends. Any beans specified are guaranteed to be
 * created by the container before this bean. Used infrequently in cases where a bean
 * does not explicitly depend on another through properties or constructor arguments,
 * but rather depends on the side effects of another bean's initialization.
 *
 * <p>May be used on any class directly or indirectly annotated with
 * {@link org.springframework.stereotype.Component} or on methods annotated
 * with {@link Bean}.
 *
 * <p>Using {@link DependsOn} at the class level has no effect unless component-scanning
 * is being used. If a {@link DependsOn}-annotated class is declared via XML,
 * {@link DependsOn} annotation metadata is ignored, and
 * {@code <bean depends-on="..."/>} is respected instead.
 *
 * @author Juergen Hoeller
 * @since 3.0
 */
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DependsOn {

    String[] value() default {};

}

注意到其中一句話了嗎?

Using {@link DependsOn} at the class level has no effect unless component-scanning
s being used.

如果用在類上面,類上面需要加@ComponentScan("xxxxx")注解。

2018年3月8日 18:44