Search code examples
javaspringspring-mvcjavabeanszk

Spring bean autowiring not work


Could anyone help on this issue? I integrate Spring with zk, and the auto-wired service bean is always null in the controller.

package com.test.MVC.controller;

@Controller
@Scope("prototype")
public class MainController extends SelectorComposer<Component>{
  private MainService mainService;

  @Override
  public void doAfterCompose(Component comp) throws Exception {
    super.doAfterCompose(comp);
    List<Map<String, Object>> list = mainService.query(null);//the mainService is always null here
  }
  @Autowired
  public void setMainService(MainService mainService) {
    this.mainService = mainService;
  }
}

package com.test.MVC.service.impl;

@Service("mainService")
public class MainServiceImpl implements MainService {//MainService: surface

  private JdbcTemplate jdbcTemplate;

  public List<Map<String, Object>> query(Integer number){...}//please ignore the content

  @Autowired
  public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {//inject bean
    this.jdbcTemplate = jdbcTemplate;
  }
}

And I did add below setting in xml file

<context:component-scan base-package="com.test.MVC" />
<context:annotation-config/>

Update: I just found the setter in controller never be invoked.


Solution

  • This is because you are searching in the ZK container and not in the spring container.

    Zk has a specific variabeleResolver for that.
    Please read : https://www.zkoss.org/wiki/ZK_Developer's_Reference/MVC/Controller/Wire_Variables