user2602807
user2602807

Reputation: 1292

Spring bean interface declaring

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?

Upvotes: 0

Views: 7391

Answers (1)

Thomas Betous
Thomas Betous

Reputation: 5133

I don't recommend you to use getBean this way. In the Spring documentation, it is written that it could be bad for performance.

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

Return an instance (possibly shared or independent) of the given bean name. Provides a measure of type safety by throwing an exception if the bean is not of the required type.

Note that callers should retain references to returned objects. There is no guarantee that this method will be implemented to be efficient. For example, it may be synchronized, or may need to run an RDBMS query.

Will ask the parent factory if the bean cannot be found in this factory instance.

It really depends of what do you want to do. Did you tought that you Workclass could be a 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
    }
}

Here the configuration file :

<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>

Your main class will have to call getBean, but only one time to get the instance of WorkClass.

Upvotes: 1

Related Questions