@DependsOn注释的逆函数 [英] Inverse of @DependsOn annotation

查看:53
本文介绍了@DependsOn注释的逆函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Spring(可能还有其他DI容器,但我使用的是Spring)可以识别@DependsOn注释.您可以使用它来标识必须在此bean之前启动的所有其他bean,例如

Spring (and presumably other DI containers, but I'm using Spring) recognises the @DependsOn annotation. You use this to identify any other beans that must be initiated BEFORE this bean, eg

@Component
@DependsOn({"initiatedFirst", "initiatedSecond"})
public class InitiatedThird {

//...

是否存在类似的注释,这意味着必须在带注释的Bean之后启动所提供的Bean?例如

Is there an analogous annotation that means that the supplied beans must be initiated AFTER the annotated bean? For example

@Component
@DependencyOf({"initiatedSecond", "initiatedThird"})
public class InitiatedFirst {

//...

当您无法访问Bean的源代码/初始化但想要事先配置一些其他Bean时,我会以为这将是一个非常普遍的用例.是否存在这样的注释?

I would have thought this would be quite a common use case for when you don't have access to the source / initialisation of a bean but want to configure some other beans beforehand. Does such an annotation exist?

推荐答案

否,但是如果您无权访问代码,仍然可以使用xml

No, but if you don't have access to code, you still can use xml

<bean id="initiatedSecond" class="..." depends-on="initiatedFirst" />
<bean id="initiateThird" class="..." depends-on="initiatedSecond" />

以此类推...

修改

其他选项是使用 BeanFactoryPostProcessor 通过 BeanDefiniton.setDependsOn(String [])添加依赖项.

Other option is to use a BeanFactoryPostProcessor to add the dependences via BeanDefiniton.setDependsOn(String[]).

例如(未测试)

public class DependencyConfigurer implements BeanFactoryPostProcessor {

    private Map<String, String[]> dependencies = new HashMap<String, String[]>();

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        for (String beanName : dependencies.keySet()) {
            BeanDefinition bd = beanFactory.getBeanDefinition(beanName);
            bd.setDependsOn(dependencies.get(beanName));
        }

    }

    public Map<String, String[]> getDependencies() {
        return dependencies;
    }

    public void setDependencies(Map<String, String[]> dependencies) {
        this.dependencies = dependencies;
    }

}

另一个选择是使一个众所周知的早期实例化bean依赖于您的bean.(看起来很丑,但可以使用).

Another option is to make a well know early instantiated bean to depends on your bean. (seems ugly but will work).

最后,您可以覆盖 AbstractApplicationContext.onRefresh()并实例化bean.

Finally you could override AbstractApplicationContext.onRefresh() and instantiate your beans.

这篇关于@DependsOn注释的逆函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆