문제

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.

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top