I've a doubt about Spring session bean. Let me try to explain what I need and what I did. I need to store on a session variable (in that case a Bean) the user_id so, when I need to create some record on db I can keep track of who did what.
To do that, for first, I created a bean and, second, I modified my application context in that way:
<bean id="UserInfo" class="net.agdev.session.UserInfo" scope="session">
<aop:scoped-proxy/>
</bean>
I read that using this :
ContextLoader.getCurrentWebApplicationContext().getBean("UserInfo");
is ppossible to access to the bean, but it's not yet clear how to fill that bean..
I tryed to read on Spring documentation how to initalize the bean and how to recall on my Class controller but I didn't find anything.
Could you suggest where to find an example or a tutorial to do that?
many thanks!
Andrea
You mean how to get the user_id into the session bean? Depending on your application this should probably happen right after the user "logged in". Meaning, if you for instance have a login webflow or controller, set the user_id in your session bean within that webflow or controller.
So if I understood your context correctly this has only very little to do with Spring itself and mostly with your application :-)
If you want other aspects of your bean initialized for instance from operations on other services you could set an init-method on the bean definition as detailed here.
By aspect programming like AspectJ. You have to set some trigger, for example after an user does something you have to read your bean and fill it the operation info that have been performed by the user.
You can use #annotation to define trigger or you can do it by spring xml file. I think you have to use an application context bean and not a session bean.
Related
I have the following session scoped bean:
#ManagedBean
#Component
#Scope(proxyMode= ScopedProxyMode.TARGET_CLASS, value="session")
public class SessionData implements Serializable {}
and I store tomcat sessions in a database. The problem is that, when the application tries to deserialize a stored session, I receive the following error:
org.apache.catalina.session.PersistentManagerBase.swapIn Error deserializing Session EE913D2ACAD49EB55EDA657A54DFA2CB: {1}
java.lang.ClassNotFoundException: de.myproject.SessionData$$EnhancerBySpringCGLIB$$768b59b9
It seems that it serialized actually the whole Spring context, and obviously there is no such class de.myproject.SessionData$$EnhancerBySpringCGLIB$$768b59b9 after server restarts, so I receive the aforementioned exception.
Is there a way to avoid this, so that the session-scoped bean is serialized properly?
UPDATE: There is an issue regards this which marked as resolved without comments, however I still face it.
Please have a try:
using: import org.springframework.test.util.AopTestUtils;
Serializable readyToSerialize = AopTestUtils.getUltimateTargetObject(yourInstance);
before serialize it.
Note: this code is usefull to understund the problem, if this work, you have to analyze the project architecture and dependecies, to better accomplish for production code. First of all, why you need to serialize a ScopedProxyMode.TARGET_CLASS
Having a bean with a scope session doesn't mean that the bean is serializable and that it can be stored in a session.
As you can guess from the name of the class, a proxy class is generated at runtime with a different name at each startup. This explains why a problem occurs at deserialization.
I guess you try to add this SessionData as an attribute of the web session. You should not. Store your POJO data in the web session without using beans.
If you use the bean to inject database connections or similar objects, forget it. You can just use session scope beans for particular contexts which don't feet your requirements I guess.
i don't know well the your task, but in my opinion a data object like this should not be a spring bean because spring bean should be business logic bean, controller bean and so on and not session dto.
for this reason i consider thag you should try to think why you want store the data of your spring bean, and try to decopled the data that you want in http session, #sessionattribute of springmvc,from the business logic bean that shoud nor be session aware.
i hooe that this can help you to change your implementation stategy in order to find the solution of your problem
I'm trying to get a better understanding of the #Autowired annotations component scanning, but all the examples I found so far use context.getBean(..) at some point to get at least one Bean to start with.
I also read that doing that is considered bad practice , but I can't seem to find any information on how to do it without context.getBean(..)
Could somebody please enlighten me with an example and information on how to do this ?
Define your bean in xml and use
<context:component-scan base-package="com" />
<mvc:annotation-driven />
Bean def
<bean id="processEngine" class="com.processEngine">
<property name="processEngineConfiguration" ref="processEngineConfiguration" />
</bean>
now you can get bean as following
#Autowired
private ProcessEngine processEngine;
how it works
spring scans the bean's recipes either from xml or java configuration. then spring creates a beanDefinitions which are 'loaded' into BeanFactory. BeanFactory triggers a set of BeanPostProcessors (BPP) which are scanning classes for particular annotations like Autowired/Resource/PostProcessor and etc. and do appropriate actions. in case when your class contains #Autowired annotation, AutowiredAnnotationBeanPostProcessor would auto wire required field (dependencies), and when creation of an object is done and all BPP worked out, object is ready to be used by the app, from this point your code can get 'ready' objects from container.
there are some cases when you would need to access this beans from the code which is out of spring's control and not managed by container. in order to do so, you would need to get the ApplicationContext (container) and call #getBean specifying either name or type. using applicationContext directly is not a good practice because there are some problems that you can come to, f.ex. id of a bean might be changed and if you refer to bean by id then NPE would be thrown.
configuration
there are several approaches to configure spring to scan the classes for finding bean recipes. one would be defining component-scan, in this case classes which are located in the path that you've set and having any of valid spring annotations like #Component, #Service, #Repository, #Controller (for web container) would be considered. another way would be specifying each bean separately using <bean> or #Bean.
examples.
if you want to create a web app then you should see DispatcherServlet with ContextLoaderListener classes. this classes would boot your app and load everything according to configuration. f.ex. here,
but if you want to create a desktop app, then you would end up with something like this
From time to time (usually when not using Spring Boot), I use something along the lines of the following code:
public static <T> T autowire(ApplicationContext ctx, T bean) {
ctx.getAutowireCapableBeanFactory().autowireBean(bean);
return bean;
}
In my main, I create an instance of the main application class that contains a few #Autowired annotations for the main services / entry points to my Spring application.
This question already has answers here:
How does a ScopedProxy decide what Session to use?
(3 answers)
Closed 7 years ago.
I am trying to use session scope bean in spring mvc with following bean definitions
<bean id="test" class="com.gk.testScope.Test" scope="session">
<property name="name" value="mytest"></property>
<aop:scoped-proxy/>
</bean>
Code for controller
#Controller
public class MyController
{
#Autowired
Test t;
#RequestMapping(value="test1",method=RequestMethod.GET)
public String test1(HttpServletRequest request) {
System.out.println("name"+t.getName());
request.getSession();
return "test1";
}
}
on running above code it prints mytest even before starting any session. Can some one explain what session scope doing here?
Below line of code does not actually create session, it gets the session already created by the servlet container.
request.getSession();
Now comes the important stuff. Bit tricky to get at first if you are new to Spring scopes.
Injecting a singleton bean in another singleton bean is intuitive and makes sense. How about you want to inject a bean which is not Singleton into a Singleton bean? The injection should happen on demand right ? So to configure this, we cant directly inject the bean which is not singleton. We inject a proxy for a non singleton bean, which in turn gets a new bean injected on demand.
<aop:scoped-proxy/>
The above tag helps create a new bean for every session(because the scope is "session") created on the server and injects in the controller on demand.
I am sure someone can explain in much simpler manner. Hope this helps.
The spring framework provides an inversion-of-control coding framework; that means you only has to concern your business logic and write down it as handler function, the spring framework would take care the rest of things and call your handler function.
For example, in a mvc spring framework, the http request handling, http session handling, the beans life-cycle management are all done in spring-framework and you only needed to write the "test1()" function that is called when client hit the URL "/test1".
When client start a HTTP session with spring web server, the framework will create a session scope, and all session scope beans will be created. When client sends a HTTP request, the framework will create a Request scope and all create request level scope beans.
Please see 6.5 Bean scopes from spring reference doc.
I wanted to know if I can pass a property to a bean I declared on a xml configuration file (for example on the applicationContext.xml):
<bean id="captchaVerifierFilter" class="org.abc.filter.CaptchaVerifierFilter"
p:useProxy="false"
p:proxyPort=""
p:proxyHost=""
p:failureUrl="/abc/main/loginfailed"
p:captchaCaptureFilter-ref="captchaCaptureFilter"
/>
I want to use the captchaVerifierFilter bean to test if a captcha is valid or not. Then I can set the failureUrl property to url "add-record" and redirect to that jsp.
How can I send a property (like failureUrl for example) through a controller. Is this possible? What should I code on the controller if it's possible?
Any idea? Thank you very much!
I think you should define both the success and the failure url as properties in your configuration and then let the filter decide which way to go.
You can change the properties of the bean if you make it accessible (by making it public or with a setter) but that is probably not want you want since it changes the property for the single bean instance in the application context which is used by several threads concurrently.
Best regards
Hacim
By default the beans in the context are in singleton scope. So when you set the value for the property failureUrl in one controller, another controller will also see this new value when it gets the bean from the context.
#Autowired works only once.
What to do to make it wire the bean every time the Servlet is recreated?
My web-app (Tomcat6 container) consists of 2 Servlets. Every servlet has private fields.
Their setters are marked with #Autowired
In the init method I use
WebApplicationContextUtils
...
autowireBean(this);
It autowires the properties marked with #Autowired once - during the initialization of the Servlet.
Any other session will see these fields values, they will not be rewired after the previous session is destroyed.
What to do to make them rewire them each time a Servlet constructor is called?
a) Put the autowiring into the constructor?
Or better 2) get a web app context and extract a bean from there?
There seems to be some misunderstanding about how the container works. Servlets are essentially singletons, you don't get a new servlet everytime someone calls the server. Storing state in private fields on a servlet is pretty much an error.
What is the scope and life-cycle of the stateful part of your request processing? If it's just the life of the request then you can take whatever on your servlet is stateful and move it into another class. Then you can define a prototype bean for that class and use getBean at the start of the request to get a new one. If you want to start getting fancy you could write a filter that puts a new bean into a ThreadLocal at the start of each request.
If your state needs to span multiple requests, you need to start keeping state or a key that points to the state storage on the web session, or look into using a conversation framework.
Try using scope as prototype for that bean #Scope("prototype")
You may try to use #Scope("session")