java - Bean injection based on a local method parameter -


i new spring , facing curious problem. have following:

class statscollector { private final list<stat> stats; private userid userid; . . . public void finduserid() {     userid = userservice.getuserid(); }  public void compilestats() {     stats.stream().foreach(stat -> {         stat.fetchstats();     }); } 

}

i using spring , want inject different list of stat's based on different userid. spring configuration has:

<util:list id="atypestats">     <value>fooa</value>     <value>bara</value> </util:list>  <util:list id="btypestats">     <value>foob</value>     <value>barb</value> </util:list> 

question: possible inject either atypestats or btypestats based on userid in code after getting service?

my problem cannot know userid in advance use constructor injection in way. userid obtained using service , need inject required list spring configuration.

in general opt not have "data" user-stats in spring config. create proper service stat lookup user id.

depending on actual scenario there few ways accomplish that: if 1 user stat list valid given application instance: can use profiles/environments conditionally load different configs or parts of configs (https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html) , combine alias.

alternatives "real" user service injecting map (maps populated given type) or injecting whole application context , manually fetching data. consider these "lazy hacks" when proper service lookup better suited (and both not flexible, testable , scaleable proper service)


Comments