0

I have a controller class :

@Controller
public class MyController {

@AutoWired
Service myservice

@RenderMapping
public display(){
    //do work with myservice
}

}

I want to invoke the method display() from an external class but I am a null pointer exception.

Here is how I am invoking the display method from an external class :

new MyController.display()

But the instance myservice is being set to null.

How can I invoke MyController.display() and ensure the instance of myservice is not set to null ?

I think the problem is since I am creating a new instance of the controller the service is then not autowired ? But since the Spring controllers are singletons perhaps I can get access to the current instance of the controller ?

Update :

The reason I am trying this is I'm adding a config option to determine which controller display method should be implemented. Perhaps I should be using a super controller to determine which controller should be implemented ?

4

2 回答 2

1

想法是:使用抽象父类!

// this class has no mapping
public abstract class MyAbstractController() {
  @Autowired
  MyService service

  public String _display(Model model, ...) {
    // here is the implementation of display with all necessary parameters
    if(determine(..)){...}
    else {...}
  }

  // this determines the behavior of sub class
  public abstract boolean determin(...);
}

@Controller
@RequestMapping(...)
public class MyController1 extends MyAbstractController {

  @RequestMapping("context/mapping1")
  public String display(Model model, ...) {
    // you just pass all necessary parameters to super class, it will process them and give you the view back.
    return super._display(model, ...);
  }

  @Override
  public boolean determine(...) {
  // your logic for this 
  }
}

@Controller
@RequestMapping(...)
public class MyController2 extends MyAbstractController {

  @RequestMapping("context/mapping2")
  public String display(Model model, ...) {
    // you just pass all necessary parameters to super class, it will process them and give you the view back.
    return super._display(model, ...);
  }

  @Override
  public boolean determine(...) {
  // your logic for this 
  }
}

希望这可以帮到你...

于 2013-10-01T12:33:50.620 回答
0

我认为问题是因为我正在创建控制器的新实例,所以服务不是自动装配的?

是的。您可以使用 Spring 中的 BeanFactory API 访问您的 bean。但是直接调用控制器听起来很可疑。你能告诉我们你想要达到什么目标吗?也许我们可以看看是否有标准的方法来做到这一点?

于 2013-10-01T10:55:03.000 回答