Question

i want pass parameter to @autowired ref like

public CoreDao {
   private String taskId;
   private final String sql = "select ....."+getTaskId()+".....";
   public CoreDao(String taskId){
     if(taskId.length != 0){
        this.taskId = taskId;
     }else{
        this.taskId = "0";
     }
     public getTaskId(){
       return this.taskId;
    }
}

xml is:

<bean id="coreDao" class="Coredao" scope="prototype">
  <constructor-arg type="java.lang.String" value=""/>
</bean>

and the CoreService is

@service
 CoreService implement ICoreService{
  @Autowired
  pirvate CoreDao;
}

and xml is

<bean id="coreService" class="CoreService" scope="prototype">
  <property name="coreDao" ref="coreDao"/>
</bean>

and i want use getBean("coreService","123") to get the bean with dynamic reference of coreDao. However,when i use getBean("coreService","123"),the exception is: error creating bean with name "coreService" defined in file ....xml,could not resolve matching constructor (hint:specify index/type/name arguments for simple parameter to avoid ambiguities. how could do that?thanks your help.

Was it helpful?

Solution

getBean(String, Object ...) is applicable to bean's constructors or factory methods. Your CoreService should have CoreService(String s) constructor in order to use this method. If you want to create many CoreService instances with different parameters, you can create a factory bean which creates all instances for you and puts them together, like

@Component
public class CoreServiceFactoryBean {

  @Autowired ApplicationContext ctx;

  public CoreService getBean(String param) {
    CoreService coreService = ctx.getBean("coreService");
    CoreDao coreDao = ctx.getBean("coreDao", parameter);
    coreService.setCoreDao(coreDao);
    return coreService;
  }
}

This way, the logic of creating bean and using it remains separate. Using factories is pretty common to configure prototype scoped beans.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top