0

I am experiencing some conceptional difficulty with the scope of some beans referenced in controllers. I have checked a lot of related questions in file and still not sure. Could someone please help me clarify it?

I am numbering the questions or statements as follows to make helper easier to address my problems.

Per my understanding from the the Spring doc, in spring web application,

1) for any controller, annotated with a @Controller, if there is a private field bean, with default bean scope, this field bean will be accessed as the singleton thus susceptible to thread issue;

2) If the field bean is marked as scope=""prototype, this field bean, within this controller, will still behave like a singleton, thus being not-thread safe.

3) To make such a field bean thread safe, we have to make the bean scoped with request or session right?

The following is a simplified example related to this question:

@Controller public Class ControllerA

@Autowired private DefinedBean db;

@RequestMapping("/testPath") public ModelAndView getPathPage(){

  this.db.setTitle("abc");
  this.db.readReportWithTitle();
  ....
  return new ModelAndView();

}

So in this example,

4) if the DefinedBean is defined through xml configuration with or without explicit scope of prototype, this DefinedBean will have synchronization issue, right?

5) To ensure this DefinedBean to be thread safe, we have to define it explicitly with request or Session.

On the other hand,

6) if we mark the controller itself with a scope of prototype explicitly, will it get rid of the non-thread safe issue with the DefinedBean field? My thought is no, this won't.

7) To make the field thread safe, if we are going to control at the controller level, we need to mark the controller with Scope="Request" as well, right?

Your comments are welcome and appreciated. If you can comment with "Correct" Or "Incorrect" or elaborate further to those numbered (1~7) statements, Myself and possible those who come later will appreciate more.

Hongbing
  • 1
  • 2

1 Answers1

0

I think you want to leave the controller be a singleton.
Here is the spring documentation that explains how to bind beans having different scopes.

This is how you would want to define the wired bean:

<bean id="db" class="DefinedBean" scope="request">
  <aop:scoped-proxy/>
</bean>

I have looked up to see how the same can be done with annotations only and I have found this.

Basically, you annotate DefinedBean with :

@Scope(value = "session", proxyMode = ScopedProxyMode.INTERFACES)
Community
  • 1
  • 1
Cristian Sevescu
  • 1,364
  • 8
  • 11