Scope of a Spring-Controller and its instance-variables - spring

Are all controllers in Spring-MVC singletons and are shared among different sessions and requests?
If so, I assume that a class-variable like
public String name;
would be the same for all requests and sessions? So that if User X makes a request and name is being set to Paul, User Z also has Paul as attribute?
In my case I do NOT want that behaviour but wondered if there is a more easier, or more cleaner OOP-way to have session/request-variables then session.getAttribute()/request.getAttribute()

To answer your first question: yes, Spring MVC controllers are singletons by default. An object field will be shared and visible for all requests and all sessions forever.
However without any synchronization you might run into all sorts of concurrency issues (race conditions, visibility). Thus your field should have volatile (and private, by the way) modifier to avoid visibility issues.
Back to your main question: in Spring you can use request- (see 4.5.4.2 Request scope) and session-scoped (see: 4.5.4.3 Session scope) beans. You can inject them to controllers and any other beans (even singletons!), but Spring makes sure each request/session has an independent instance.
Only thing to remember when injecting request- and session-scoped beans into singletons is to wrap them in scoped proxy (example taken from 4.5.4.5 Scoped beans as dependencies):
<!-- an HTTP Session-scoped bean exposed as a proxy -->
<bean id="userPreferences" class="com.foo.UserPreferences" scope="session">
<!-- instructs the container to proxy the surrounding bean -->
<aop:scoped-proxy/>
</bean>

Yes, controllers in Spring-MVC are singletons. Between multiple requests your class variable get shared and might result into ambiguity.
You can use #Scope("request") annotation above your controller to avoid such ambiguity.

Related

how does scoped proxy works internally in Spring

consider a case when a prototype-scoped bean is injected into a singleton scoped bean,
when we try to access prototype-scoped bean using the singleton-scoped bean, we are returned with the same bean every time i.e. the bean injected at the time of singleton initialization.
if we want to get different instances everytime we use a scoped proxy.
I did not get the concept how this scoped proxy works behind the stage and how it magically gives us a new instance even if the bean is present inside a singleton.
From the Spring documentation:
3.4.4.5. Scoped beans as dependencies
Being able to define a bean scoped to a HTTP request or Session (or indeed a custom scope of your own devising) is all very well, but one of the main value-adds of the Spring IoC container is that it manages not only the instantiation of your objects (beans), but also the wiring up of collaborators (or dependencies). If you want to inject a (for example) HTTP request scoped bean into another bean, you will need to inject an AOP proxy in place of the scoped bean. That is, you need to inject a proxy object that exposes the same public interface as the scoped object, but that is smart enough to be able to retrieve the real, target object from the relevant scope (for example a HTTP request) and delegate method calls onto the real object.
…
To create such a proxy, you need only to insert a child element into a scoped bean definition (you may also need the CGLIB library on your classpath so that the container can effect class-based proxying; you will also need to be using Appendix A, XML Schema-based configuration). So, just why do you need this element in the definition of beans scoped at the request, session, globalSession and 'insert your custom scope here' level? The reason is best explained by picking apart the following bean definition (please note that the following 'userPreferences' bean definition as it stands is incomplete):
<bean id="userPreferences" class="com.foo.UserPreferences" scope="session"/>
<bean id="userManager" class="com.foo.UserManager">
<property name="userPreferences" ref="userPreferences"/>
</bean>

Real use case of proptotype scope of spring beans

Waht is a real example for such kind of stuff? I have already looked through this post, but the answers to this post seem inconclusive to me. Also there is an advice: "As a rule, use the prototype scope for all stateful beans and the singleton scope for stateless beans" - from spring reference, but why do we need our services to be stateful? We can just share this state as a simple dto among services' calls.
One popular use of it is to associate separate instance of a bean to each HTTP session.
Consider your have a bean class called UserConfig. You can set this bean with prototype scope, and configure such that each new HTTP session has its own UserConfig bean instance. (Spring MVC has its own scope called "session" for this purpose, but the concept is similar)
Also the user can change your site configuration, and the changed state is saved on its own instance of the bean (as opposed of altering the global single instance if you set it into singleton scope)

What is the prototype Spring Bean used for?

By default, the Bean created by Spring is singleton. They are thread-safe because they are stateless. When we want Spring to create a stateful Bean, we need to use prototype scope for the Bean definition. We need to take care of the thread-safe issues for them. All stateless Bean will be polluted when they are injected by the prototype bean. So, I just can not image where we can use the prototype scope. Can you give some typical scenario that we can / need to use prototype Spring Bean? Also how can we void the stateful pollution on other singleton beans?
There are many reasons to use prototype scope, e.g., any time you'd use "new" instead of using a singleton. A per-user bean, a per-request bean, a collection of unique beans, etc. After all, in any non-trivial application, don't you use non-singletons far more than singletons?
Singleton-scoped beans aren't thread-safe simply because they're singletons–they must be written to be thread-safe. They don't become thread-safe magically. A bean's scope is just that, its scope: it doesn't make the bean appropriate for the particular scope–that's up to the developer.
I perceive prototype scoped beans as an alternative to factory classes used to create objects. The difference is in case of prototype beans spring will save you some code for dependency injection and will also automatically proxy your objects for transactions etc. when appropriate.
I myself prefer the factory approach. One reasonable scenario for prototype scope I encountered was a stateful object, needed by different known beans and each required its own copy. A dedicated factory class would be redundant in this scenario since I did not need to create objects on the fly but only during other beans' instantiation.

Trying to supply an alternative implementation for Spring's FilterChainProxy

I'm working on an application using Spring security.
The application is extensible and I would like to block extensions from programmatically changing the filters in the filter chain map of Spring's FilterChainProxy. What I intend to do is the following:
Implement a CustomFilterChainProxy implementing all of FilterChainProxy's implemented interfaces (Filter, InitializingBean, ApplicationContextAware). In it I will hold a private FilterChainProxy member and delegate all of the interface calls to it.
Use Spring's DelegatingFilterProxy by declaring in the web.xml file:
<filter>
<filter-name>customSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
In the Spring configuration files, instead of using Spring's FilterChainProxy directly I will have my bean have the CustomFilterChainProxy as its class, as follows:
<bean id="customSecurityFilterChain" class="....CustomFilterChainProxy">
<security:filter-chain-map ...>
<security:filter-chain pattern="..." filters="..." />
<security:filter-chain pattern="..." filters="..." />
...
</security:filter-chain-map>
</bean>
In order to be able to set the filter chain map during Spring bean loading I must supply a setter in my CustomFilterChainProxy class. That I will do. And in order to prevent setting the filter chain map after Spring bean loading I will make sure that after bean construction (in a #PostConstruct method) an exception will be thrown from that setter.
By having a CustomFilterChainProxy instead of a FilterChainProxy, am I causing any Spring process to malfunction?
I saw the only Spring class referencing the FilterChainProxy object itself is FilterChainProxyPostProcessor but couldn't find out if this should affect my implementation choice. Any input?
Thanks a lot.
This is unlikely to be sufficient to protect you from malicious extension code.
If the extension can access your bean, then it can also just access the original FilterChainProxy through the ApplicationContext. In fact, it can probably access any other bean in the same configuration, so it could potentially:
Load user account data, including passwords
Modify or read settings on other beans to break the system
Use reflection to read instance fields directly
Modify the current security context
Lots of other nasty things depending on what you are using
If you have untrusted code in your app then you would need to use a SecurityManager to prevent this kind of thing and you can then also prevent access to Spring Security classes. Configuring a SecurityManager can be a pain, but it's probably the only option if you have code you don't trust running in the same VM.
Update: If your only concern is preventing anyone from calling the setFilterChainMap method then overriding this method will obviously prevent anyone from accidentally calling this through a reference to your bean (this method is actually deprecated in 3.1 in favour of a constructor. However, it's not clear from your question why someone would obtain a reference to your instance rather than the original bean, or why this is your main concern. The FilterChainProxy is not normally accessed by user code in an application. To do so, you'd have to explicitly request it from the bean factory.

Spring injection and object instantiation

I am trying to better understand Spring instantiation of beans. To illustrate my doubts, let's assume we have a Service class being wired in a Controller, here are the questions:
How will Spring manage the lifecycle
of the Controller? Will a new object
be created per request?
Once a Service is instantiaded and
wired to a Controller, will Spring
re-use that object reference to wire
it in to other beans?
Like Servlets, Controllers' lifecycle spans beyond requests. All of controllers in the application are instantiated only once when application is started; afterwards those objects are re-used to service all requests.
As Bozho pointed out, by default all beans are in singleton scope, therefore they will be re-used everywhere, unless specified otherwise.
The default scope is singleton, which means beans will be re-used (i.e. 1) no, a new object will not be created per request, and 2) yes, the object reference will be reused).
This can all be configured. Have a look at http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-scopes.
It all depends on the bean scope. By default all beans are in singleton scope - that is, they are instantiated by the container only once.
If you specify #Scope("request") (or the xml equivalent) then the same service object (singleton) will be injected in all instances of the request-scoped controller. (But you rarely need request-scoped controllers)

Resources