Using session-scoped object in singleton in Spring - spring

I have a problem with one of my beans. I have a bean, which has a singleton scope and second bean which has session scope.
I'm using java based config in my spring app, I added proxy mode to my session scope bean, but it throws exception when I'm tryign to use that (session scoped) bean:
Method threw 'org.springframework.beans.factory.BeanCreationException' exception. Cannot evaluate my-bean-full-name$$EnhanceBySpringCGLIB#ID.toString()
From what I have read here http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-factory-scopes-other-injection-proxies
I thought that only thing which I have to do is to add
#Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
to my bean class (which also has #Component annotation and it is scanned by Spring)

The thing which I was missing was this line in my web app initializer:
servletContext.addListener(new RequestContextListener());
After that, bean has been injected

Related

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

How #RequestMapping internally works in Spring Boot?

#RestController
#RequestMapping("/employee")
public class Employee {
#RequestMapping("/save")
public void saveEmployee() {
// saving employee
}
}
How does #RequestMapping will work internally to map the request to the saveEmployee method?
During application startup, Spring will identify all Beans by way of XML Config, Java Config, or Component Scanning and store them in the ApplicationContext.
Spring Boot autoconfigures many Beans for you, including RequestMappingHandlerMapping.
When this Bean is initialized it scans the ApplicationContext for any Beans annotated with #Controller.
Then it iterates over each Controller bean and looks for methods annotated with #RequestMapping. Finally it persists these mapping/handler pairs in the MappingRegistry
The DispatcherServlet is the central HTTP request handler for your application and it will search the ApplicationContext for any Beans that implement the HandlerMapping interface, which the RequestMappingHandlerMapping Bean does (by way of inheritance).
Then it iterates over these beans asking them to resolve the corresponding handler for this request. The RequestMappingHandlerMapping bean will resolve the handler by searching its MappingRegistry.
When a match is found, the handler method is eventually invoked.

Spring MVC: How autowiring of HttpSession works?

I would like to know how autowiring of HttpSession works.
If we declare like below:
#Autowired
private HttpSession httpSession;
When exactly in the Spring workflow, httpSession variable declared above will be initialized with request.getSession(true)?
I don't understand why you want to autowire HttpSession but here is how autowiring works.
To Autowire a class you need to specify it as a bean either by using annotations (#Controller, #Service, #Repository, #Component) or by declaring #Bean in config class. Once you define a bean Spring autowires or constructs the objects when the spring context initializes (during server startup for webapp and you explicitly initialize spring context in case console/standalone app).
Since HttpSession can only be fetched from HttpServletRequest object, you cannot initialize it during application startup because there is no HttpServletRequest during startup. If you want some logic to implement before fetching the HttpSession you can create a util method like this
public getHttpSession(HttpServletRequest request) {
// put your logic here and return session object
}

spring access beans during context initialisation

I want to access the Spring Applciation Context , when the entityManagerFactory is getting initialised.
We can use ApplicationContextAware , but the entityManagerFactory gets instantiated before our ApplicationContextAware bean is initialised.
Share if anybody has done something like this .
You could subclass entitymanagerfactory and give it a constructor with ApplicationContext, and wire the context into the constructor.
Note that tampering with the applicationcontext while it's still being initialized is strongly discouraged.
Configure the bean to use ApplicationContextAware and then set the SessionFactory bean's depends-on attribute to the context aware bean. This should cause the bean to be created prior to the sessionFactory.

jsf2 spring managed bean calling constructor and postconstruct only on tomcatstartup

I am using JSF+Spring project my spring maanged bean is ViewScoped
my saving state is client.
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>client</param-value>
</context-param>
Following is my bean i found that constructor of bean and postconstruct method got call only on tomcat startup when it is spring managed bean instead if it is JSF managed bean constructor and postconstruct got call on every page refresh.
Is it the real behavior if i want to call method on page refresh every time under spring managed bean what should id do ?
#Component
#ViewScoped
public class DataTableBean implements Serializable{
public DataTableBean() {
super();
}
#PostConstruct
private void loadDataData(){
System.out.println("Post constructing");
}
}
The #Component is a Spring specific annotation to manage beans by Spring. The #ViewScoped is a JSF specific annotation to specify the scope of a JSF managed bean #ManagedBean. JSF specific scope annotations does not work on a Spring managed bean at all. You should use the Spring specific #Scope annotation instead.
So, either just manage the bean by JSF:
#ManagedBean
#ViewScoped
Or homegrow a Spring "view" scope (this is namely not one of the default scopes available in Spring):
#Component
#Scope("view")

Resources