Scope 'session' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton - spring

I use JSF with Spring security. I implement it.
My code:
#Named("userDetailsManagerImpl")
#Scope("application")
public class UserDetailBusinessImpl implements UserDetailsService {
#Inject
private MenuBackingBean menu;
}
Everything seem to be good. However I must define MenuBackingBean is application scope. I only want session scope for it. So I change scope to session, but I got an error below:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDetailsManagerImpl': Scope 'session' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton
I think this error cause by spring security set application for default scope.
I searched on Google but have no answer for this problem (maybe I have no right keyword searching). Please help me to solve, thank you
More info I used:
JSF 2.0
Spring security 3.1.2
Named and Inject from JSR 330
Scope annotation from springframework package

I suppose that you have this code somewhere:
#Inject
private YourSessionBean yourSessionBean;
// later in some method
this.yourSessionBean.doSomething();
Try to use javax.inject.Provider for all these cases:
#Inject
private Provider<YourSessionBean> yourSessionBeanProvider;
// later in some method
this.yourSessionBeanProvider.get().doSomething();

Related

Spring boot getbean vs autowired

I am new to spring boot , I have confusion that
#Autowired
serviceDemo serviceDemo
and getting bean from ApplicationContext is same or different?
and if they are same then which method should I use
It depends on what you’re trying to achieve, but to sum it up;
#Bean registers the instance in the application scope. That way it is accessible for later use.
#Autowired actually asks for an instance of a specific bean already registered in the scope.
Although it’s not exactly the same, you can consider for instance the #Service annotation. It tells spring that the class is a service and registers a bean of it in the scope. If you then have a different class, say a controller (#Controller or #RestController depending on your use case) and simply try to access the service you created you’ll most likely get an error thrown at you. This is because although your IDE might recognize the service location, spring doesn’t. Adding the #Autowired sets a “link” between the bean and the instantiation at the time of booting up your app.

No FacesContext found in JoinFaces ViewScope

We are currently migrating a rather big project from JavaEE (Wildfly) to Spring Boot 2.0.5 using JoinFaces 3.2.5 for JSF support. Unfortunately when starting the server we always get the following message:
Scope 'view' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No FacesContext found.
The problematic UI bean is a Spring Component additionally annotated with javax.faces.view.ViewScoped (like class StarterMBean in the joinfaces-maven-jar-example).
Is there anything special we have to be careful about, e.g. forbidden dependencies, special configurations etc?
We are thankful for every hint!
You have an singleton/application scoped bean which has a direct or indirect dependency on a view scoped bean. This forces the BeanFactory to construct the view scoped bean when the application starts, but view scoped beans can only be used in threads which are currently processing a JSF request.
There are multiple ways to solve this problem:
Try to model your beans to only have dependencies to beans with the same or a higher scope. (So application scoped beans can only use application scoped beans, view scoped beans can use view, session or application scoped ones and so on)
When you are 100% sure your application scoped bean will only use the view scoped one during the processing of a JSF request you can automatically or manually wrap the bean in a scoped proxy.
To get a scoped proxy automcatically, change #ViewScoped to #Scope(scopeName = "view", proxyMode = ScopedProxyMode.TARGET_CLASS)
If you have no access to the view scoped bean, you can declare the injection point as ObjectProvider<> in order to get a scoped proxy.
More information about this problem can be found here: https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#beans-factory-scopes-other-injection

injecting spring beans into non-singleton classes

is it possible to inject spring beans into a polling filter class (FClass) controlled by a scheduler job?
i don't quite understand how singleton applies here.
i understand spring beans are singleton so in order to inject the spring beans into class FClass. i need to define FClass as a bean and add the DI as property etc..
so how do i know if FClass should be a singleton? i assume only classes that are singletons can be created and beans and have DI done to them.
my problem is :
i need to be able to inject my facade bean xfacade into FClass. x_facacde handles the dao object. it has Y_dao and a Z_hibernate session beans injected as DI.
when i tried to create a spring bean of StatusPollingFilter (FClass) and injected the facade bean - i got a null and the setter is never called for the injection in debug mode.
the problem:
i'm thought it might be something to do with the thread / scheduler nature of StatusPollingFilter, and since spring beans are singletons it might not work due to that.
i'm thinking of creating a factory for the StatusPollingFilter (FClass). but need to know if this is correct thing and i'm on right track before i do too much work and realize even that doesn't work as the problem might be somewhere else. ideally i just want to update a table in the easiest possible way. but i have to use hibernate as the DAO exists but hibernate is configured using
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
with /hibernate/TopoObject.hbm.xml
files.
so no matter how i try this i always get null pointer exception on session or injected facade bean.
reading some of the QA's here seems like because StatusPollingFilter is instantiated using the scheduler and not spring it cant be aware of the DI beans. so would the above factory pattern help here.
I may have an additional problem but i'll cross that bridge when i come to it. but just to mention briefly, in case anyone is aware of issues that i might hit ... not sure what / how the scheduler would invoke the factory for an instance as its all controlled by 3rd party api - which invokes a StatusPollingFilter but i'm assuming if i pass in the factory as the class and parameter it would find its way through... but initial part is the main question. please ignore the latter waffle. thanks in advance.
Actually :
i assume only classes that are singletons can be created
is where you are wrong.
A bean is just a class that you let spring instantiate. By default, they are created as singleton but you can specify the scope on your bean using the attribute scope (quite surprisingly). The value you can specify are those specified in the documentation here
So one thing you have to be careful with is the injection of beans scoped as prototype or request into singletons.
having read more - i have come across the ans.
because the StatusPollingFilter object is under control of scheduler (i knew that scheduler had something to do with it) then it is unaware of the spring beans which is why i keep getting null when i try injecting the bean.
i created a class:
ApplicationContextProvider implements ApplicationContextAware
added static access
private static ApplicationContext appContext;
did a setter for it :
public void setApplicationContext(ApplicationContext context)
{
appContext = context;
}
and added
public static Object getBean(String beanName) throws BeansException
{
return appContext.getBean(beanName);
}
used in code as :
EvoTAMDAOFacade evoDao = (EvoTAMDAOFacade) ApplicationContextProvider.getBean("evoDaoFacade");
i now have access to the facade bean and all injected beans into facade.
i still have an issue with hibernate session but thats prob due to some other issue.
pt here is i don't have access to the bean as its not in control of the spring container so i needed to somehow get it , probably could have done it via the factory method but why mess around when there a simpler way.
thanks for help by anyone who may have posted or tried to understand my problem.

Spring: Serialization of session scoped bean

I have a Spring bean with scope session. This bean holds a reference to another singleton bean which is not serializable. What is the best approach if I want to serialize the session scoped bean?
The same question is already asked here: Spring session-scoped beans (controllers) and references to services, in terms of serialization
The accepted answer is that:
[...]this issue is resolved in spring 3.0 by providing a proxy of non-serializable beans, which obtains an instance from the current application context
As far as I understand the speaker in the linked video it should "just work". But in my case it doesn't! When I try to serialize my session scoped bean i get a NotSerializableException.
How can I solve this problem?
You need to instruct Spring to create that proxy. In XML-based config, via <aop:scoped-proxy/> tag, in component-scan mode via annotation:
#Scope(proxyMode = ScopedProxyMode.INTERFACES)
on your controller class.
You may mark singleton reference field as transient. Then check How to execute method after deserialization and load reference from ApplicationContext.
Also, please provide stacktrace.
P.S.
It is not too good idea to use session passivation.

Spring Standard Bean Injection vs. Autowiring

As far as I understand When Using Dependency Injection all bean are initializing on Start.
<bean id="userPreferences" class="com.foo.UserPreferences">
</bean>
<!-- a singleton-scoped bean injected to the above bean -->
<bean id="userService" class="com.foo.SimpleUserService">
<!-- a reference to the userPreferences bean -->
<property name="userPreferences" ref="userPreferences"/>
</bean>
and the configuration above means that userService and userPreferences created when application starts. Is it correct?
When using Autowiring and using <context:component-scan>
public class SimpleUserService{
#Autowired
UserPreferences userPreferences;
//omitted
}
1) Is userPreference created on Application init?
2) What is the default scope for bean injected by autowire and how can we change it?
3) How affects bean creation and bean injection?
Hope I made myself clear.
First of all you should add #Service or #Component to the SimpleUserService class.
1 Yes, the ONE instance of UserPreferences is created at application intialization
2 Default scope is singleton, You can change it with the #Scope annotation (#See Spring Reference: 3.11.4.4 Specifying bean scope)
3 Component scan and XML configuration work in the same way (life cycle)
Maybe you should spend some time in understanding the Spring life cycle. You need to understand that Spring works a bit in this way (not 100% correct):
first it creates a pool of beans
then it injects the properties into the beans
But it does NOT work this way: taking a class, look what references it needs creating this references (recursive) and then creating the class.
If you understand this, then you will also understand, that the #Scope of a bean is defined at the bean declaration/class, but not at the references.
1) Is userPreference created on
Application init?
In either case userPreferences is initialized when Spring Context is loaded. You can change this behavior by adding lazy-init="true" to the bean configuration.
2) What is the default scope for bean
injected by autowire and how can we
change it?
The scope of what is injected is all beans loaded into Spring. If you import an XML configuration from another project, it too would be included. I'm not sure if you can limit your scope.
3) How affects bean creation and bean
injection?
Whether is autowired, or configured via XML, the behavior should be the same. I prefer explicitly defining dependencies over automatic annotations. Then again I also like strongly typed languages.
the configuration above means that userService and userPreferences created when application starts. Is it correct?
Yes
Is userPreference created on Application init?
Yes
What is the default scope for bean injected by autowire and how can we change it?
The default scope is always "singleton". This can be changed either using #Scope with #Bean or the scope XML attribute on <bean>.
How affects bean creation and bean injection?
This isn't a clear question. If you change the bean scope, you change when it gets created (start of application, on each request, on each session, etc). The wiring configuration remains the same, only the lifecycle changes.
The #autowired notation is an obsolete way to say #inject. THe latter is a feature of JavaEE 6.
stackoverflow.com/questions/7142622/what-is-the-difference-between-inject-and-autowired-in-spring-framework-which

Resources