Spring bean interface declaring

时间:2015-07-13 21:05:17

标签: java spring spring-bean

I have a work class :

public class WorkClass implements ApplicationContextAware {
   ... // has access to ApplicationContext
}

Have some useful interface :

public interface UsefulInterface {
    void doUseful();
}

Have some impl class that can do much more:

public class CanDoAlmostEverything implements UsefulInterface {
    ...
}

I want to provide UsefulInterface implementation (via CanDoAlmostEverything) to WorkClass using Spring, but NOT to access any other CanDoAlmostEverything methods exept "doUseful"

In other words I want to declare my bean[s] like :

<bean id="workerA" interface="UsefulInterface" class="CanDoAlmostEverything"/>
<bean id="workerB" interface="UsefulInterface" class="AnotherUsefulImpl"/>

WorkClass will know about interface impl only during runtime and code must look like:

String todayWorker = getWorkerNameFromDataBase();
UsefulInterface worker = appCtx.getBean(todayWorker, UsefulInterface.class);
worker.doUseful();

Is it possible? And how it must look like?

1 个答案:

答案 0 :(得分:1)

我建议您不要这样使用getBean。在Spring文档中,写道它可能对性能有害。

http://docs.spring.io/spring/docs/1.0.2/api/org/springframework/beans/factory/BeanFactory.html#getBean%28java.lang.String%29

  

返回给定bean的实例(可能是共享的或独立的)   名称。如果出现异常,则提供类型安全措施   bean不是必需的类型。

     

请注意,调用者应保留对返回对象的引用。那里   不能保证这种方法的实施效率很高。   例如,它可能是同步的,或者可能需要运行RDBMS   查询。

     

将询问父工厂是否在此找不到bean   工厂实例。

这取决于你想做什么。您是否认为Workclass可能是一个bean?

public class WorkClass implements ApplicationContextAware {
    private UsefulInterface workerA;
    private UsefulInterface workerB;

    public void setWorkerA(UsefulInterface workerA) {
        this.workerA = workerA;
    }

    public void setWorkerB(UsefulInterface workerB) {
        this.workerB = workerB;
    }

    public void work() {
        UsefulInterface workerToUse;
        if(condition) {
            workerToUse = workerA;
        } else {
            workerToUse = workerB;
        }
        // treatment
    }
}

这里是配置文件:

<bean id="workerA" interface="UsefulInterface" class="CanDoAlmostEverything"/>
<bean id="workerB" interface="UsefulInterface" class="AnotherUsefulImpl"/>
<bean id="mainWorker" class="package.of.WorkClass">
     <property name="workerA" ref="workerA" />
     <property name="workerB" ref="workerB" />
</bean>

您的主类必须调用getBean,但只能调用一次WorkClass实例。