java - Spring bean interface declaring -


i have work class :

public class workclass implements applicationcontextaware {    ... // has access applicationcontext } 

have useful interface :

public interface usefulinterface {     void douseful(); } 

have impl class can more:

public class candoalmosteverything implements usefulinterface {     ... } 

i want provide usefulinterface implementation (via candoalmosteverything) workclass using spring, not access other candoalmosteverything methods exept "douseful"

in other words want declare bean[s] :

<bean id="workera" interface="usefulinterface" class="candoalmosteverything"/> <bean id="workerb" interface="usefulinterface" class="anotherusefulimpl"/> 

workclass know interface impl during runtime , code must like:

string todayworker = getworkernamefromdatabase(); usefulinterface worker = appctx.getbean(todayworker, usefulinterface.class); worker.douseful(); 

is possible? , how must like?

i don't recommend use getbean way. in spring documentation, written bad performance.

http://docs.spring.io/spring/docs/1.0.2/api/org/springframework/beans/factory/beanfactory.html#getbean%28java.lang.string%29

return instance (possibly shared or independent) of given bean name. provides measure of type safety throwing exception if bean not of required type.

note callers should retain references returned objects. there no guarantee method implemented efficient. example, may synchronized, or may need run rdbms query.

will ask parent factory if bean cannot found in factory instance.

it depends of want do. did tought 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     } } 

here 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 have call getbean, 1 time instance of workclass.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -