0
votes

i have a simple pojo UserQuota with 1 field quota in it:

@Component
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public interface UserQuota {
    public int getQuota();
    public void setQuota(int quota);
}

now, i used two different browser windows (firefox and chrome) to log into my web application as two different users. to my surprise, when i set the value of quota (with setQuota) from one session, the new value becomes available to the other session (when getQuota is called). i was expecting each user session will have its own bean instance; isn't that what session scoped bean in spring is for?

i must be missing something. what could it be?

edit:

the implementation class looks like this:

@Component
public class UserQuotaImpl implements UserQuota {

    private int quota;

    /**
     * @return the quota
     */
    public int getQuota() {
        return quota;
    }

    /**
     * @param quota the quota to set
     */
    public void setQuota(int quota) {
        this.quota = quota;
    }

}

and finally here is how i use the session bean:

@Component
public class UserQuotaHandler {

    @Autowired
    private UserQuota userQuota;

    public void checkAndUpdateQuota() {
        int quota = userQuota.getQuota();

        // i use my business logic to decide whether the quota needs an update
        if(myBusinessLogic) {
            userQuota.setQuota(someNewValue);
        }
    }

}

i am using context:component-scan in my xml config file. it may be noted that most of my other autowired beans are singleton beans which seem to have been working as expected

1
Please show how you inject and use the bean.Savior
i have updated my question as requestedTanvir
Where is the implementation class? You'll want to annotate that with the @Scope, not the interface, afaik.Savior
i included my implementation class in the question. let me check what happens if i move the @Scope annotation from interface to implementation. will get back with the outcomeTanvir
excellent. that was it. now i am getting the expected behavior. many thanks. can you please post the solution as an answer so that i can accept it; also if you could add a bit of explanation / reference to why it doesn't work when the interface is annotated, that would be much appreciatedTanvir

1 Answers

1
votes

You'll want to annotate your concrete bean class with the session @Scope, UserQuotaImpl in your case.

Spring ignores the @Scope on any superclasses or superinterfaces of your concrete class. Since your type doesn't have any explicit @Scope annotations

@Component
public class UserQuotaImpl implements UserQuota {

Spring assumes you meant to make it a singleton bean.