Operations allowed in stateless session bean's business methods - ejb-3.0

Given a Stateless Session Bean with a Local Business Interface and CMT (Container Managed Transaction). All methods of the SLSB have Transaction Attribute set to "REQUIRED".
The Bean also has an injected field sessionContext of type SessionContext.
The question is: "Which two operations are allowed in a bean business method?"
According to EJB 3.0 Core Specification, Chapter 4 Table 2:
SessionContext methods: getBusinessObject,getEJBHome, getEJBLocalHome,
getCallerPrincipal, isCallerInRole, getRollbackOnly, setRollbackOnly,
getEJBObject, getEJBLocalObject,
getTimerService,getInvokedBusinessInterface, lookup JNDI access to
java:comp/env
Since this is a question of a simulator for SCBCD (1z0-860) Certification for Java EE 5, the provided answer is:
sessionContex.setRollbackOnly()
sessionContext.getBusinessObject()
Other two possible options were "sessionContext.getEJBObject" and "sessionContext.getEJBLocalObject".
Having the SLSB a Business Local Interface, my second choice, after setRollbackOnly was to call getEJBLocalObject which actually is not the right answer.
Is the asnwer provided by simulator correct? If yes:
Anyone can help me to better understand this scenario?
Regards,
Pierluigi

Of the given options:
sessionContext.setRollbackOnly - Can be called because the bean uses container-managed transactions
sessionContext.getBusinessObject - Can be called because the bean has a business interface
sessionContext.getEJBObject - Cannot be called because only beans that have a remote component view can call this method
sessionContext.getEJBLocalObject - Cannot be called because only beans that have a local component view can call this method

Related

getting bean id of target class in advice

I have a few classes that interact with databases (more than one). Some classes are reused so for example "obs.table1" is used to interact with table1 in database "obs" while "ref.table1" is used to interact with table1 in database "ref". These databases are at different URLs and each gets its own connection pool, etc... obs.table1 and ref.table1 are both instances of MyTable1Class, defined in beans file.
I have a pointcut that intercepts calls to methods annotated with #Transactional or with a custom annotation #MyTablesAnnotation and have it set so those calls will all get routed into a #Around advice.
This all works and the flow through the advice is correct.
What I am trying to add is reporting on what is going on in there. Currently I can tell where in there I am, but I can't tell if it was obs.table1 or ref.table1 object that got me there.
Is there a way to extract the bean id of the object on whose method the advice was invoked on?
ProceedingJoinPoint that is passed to the method the only thing I do with it is call a .proceed on it and the rest is just various checks and catches. I see that I can get either the target class or proxy class out of it, but... not sure how to go from there to knowing what the bean id was.
Is it possible?
Firstly it is not recommended to depend on bean id as it creates tight coupling with framework.
To quote from docs Note that it is not usually recommended that an object depend on its bean name, as this represents a potentially brittle dependence on external configuration, as well as a possibly unnecessary dependence on a Spring API.
Now to answer your question yes it is possible to fetch the name of bean via org.springframework.beans.factory.BeanNameAware.
The class for which you require the bean name should implement it and spring will auto-magically inject the name of the bean. However there is a gotcha which you should be aware and is mentioned in docs here

Regarding Instance in Spring mvc web application development

I am new to spring mvc web development. I have one query.
Suppose we are having different service classes. So do we have one instance of those classes per request OR only single instance of that class gets create. Actually i want to use instance variables , so with each request new instance will get created or it will be like singleton type of behavior. Hopefully i am able to explain my question.
you can have either, the default is a singleton - one instance. But this can be changed using bean scope.
obligatory link to offical docs correct chapter
(personally never needed to use anything other singleton)
If you have not defined any scope explicitly, it will be singleton by default, singleton means there will be one object per spring container, for your context, one object for all your request threads. In case of singleton scope, be cautious while using member variables, because thread safety comes into picture.
If you are modifying state of a member variable inside your singleton scoped bean, you need to write thread safe code because multiple threads are accessing your member variable and a race condition may occur.
Moreover, you can define other scopes too using #Scope at the class level(i.e above #Component) or at method level above #Bean annotations.
Generally, we keep using the default scope (i.e singleton scope), this way spring container also does not waste time in creating the new object of the bean asked for, though it would be a little overhead creating an object on each request thread.
If you want a new object on every bean injection, you can have prototype scope for that bean.

How to architect/annotate beans so they come from session after 1st time creation from persistence layer

I am early in the architecting phase of a project -- there is no code to post. Basically, I have a controller retrieving a "Model bean" which roughly corresponds to the page/form: so it has form information (what checkboxes are selected, etc.) -- and also contains domain beans (database entity info).
How to get Spring to create "default" info for the "model beans" on the first use, but retrieve from session thereafter. And similarly, how to get Spring to create domain bean from persistence layer 1st time, but retrieve it from the session thereafter? EDIT: Using just annotations.
If I got your question right. This is what I have done.
Under LoginController I have condition to authenticate user. Then I add the user info in a bean and redirectAttrs.addFlashAttribute("mySession", thisIsUserSessionBean);
This is redirected to another controller called LandingController. Annotation under LandingController is something like below. Note: #SesssionAttributes annotation. You can add any information under this session object. My suggestion, keep the bean smaller for performance sake.
#Controller
#RequestMapping(value = "/homepage")
#SessionAttributes({"mySession"})
public class LandingController
I would not prefer to have domain bean sticked in session.

In spring batch framework, what is the difference between 'lazy-init=true' and 'scope=step'?

When I defined a 'MethodInvokingFactory' bean with 'scope=step', I got an error that the type of the bean can't be determined. It worked fine when I replaced 'scope=step' with 'lazy-init=true'. As per my knowledge, both are used for the late binding of the beans, except for that one difference. Are there any other differences between these two ways? Also, is my usage correct?
Please let me know your thoughts about this.
To answer to your question from low-level perspective:
lazy-init="true" means that bean will not be instantiated when the context is created, but will be created when it is referred e.g. by another bean. I think this is clear, also from #AravindA comment.
Scoped bean works in different manner. When context is created this bean is wrapped into additional proxy object (by default created by CGLIB), which is passed to the bean that refers it (this proxy is by default singleton, e.g. shared). So each time the method is invoked on the proxy in runtime Spring intersects the call, requests the factory to return the instance of the bean and invokes the method on that bean. The factory in its turn may lookup for "real" bean instance e.g. in HTTP request ("request" scope) or HTTP session ("session" scope) and/or create new instance if necessary. Late instantiation allows to initialize the scoped bean with "runtime" (scope) values, e.g. values from HTTP request/session which are obviously undefined when context was created. In particular "step"-scoped beans are bound to thread local (remember that steps are run in parallel for partitioning). So, scoped beans are dereferred when you call a method on them. Finally one can easily break this elegant Spring "ideology" by calling any method on scoped bean just after it is set to another bean (e.g. in the setter) :)
One thing to understand about lazy-initialization is that even though a bean
definition may be marked up as being lazy-initialized, if the lazy-initialized
bean is the dependency of a singleton bean that is not lazy-initialized, when the
ApplicationContext is eagerly pre-instantiating the singleton, it will have to
satisfy all of the singletons dependencies, one of which will be the
lazy-initialized bean!
Using a scope of Step is required in order to use late binding since the bean
cannot actually be instantiated until the Step starts, which allows the
attributes to be found. Because it is not part of the Spring container by
default, the scope must be added explicitly, either by using the batch namespace
or by including a bean definition explicitly for the StepScope (but not both):
<bean class="org.springframework.batch.core.scope.StepScope" />
Read here and here for more info
The scope="step" has nothing to do with Lazy initialization . It is use for late binding of parameters inside a "Step" .
the step scope is specifically for latebinding of job/step attributes and not really for late-binding of beans, meaning the spring bean context/factory will enhance stepscoped beans and look for attributes to set, e.g.
value="#{jobParameters[input.file.name]}

Overriding the bean defined in parent context in a child context

Our app has a requirement to support multi-tenancy. Each of the boarded customer might potentially override 1 or more beans or some properties of a bean defined at the core platform level (common code/definitions). I am wondering what is the best way to handle this.
Spring allows you to redefine the same bean name multiple times, and takes the last bean definition processed for a given name to be the one that wins. So for example, your could have an XML file defining your core beans, and import that in a client-specific XML file, which also redefines some of those beans. It's a bit fragile, though, since there's no mechanism to specifically say "this bean definition is an override".
I've found that the cleanest way to handle this is using the new #Bean-syntax introduced in Spring 3. Rather than defining beans as XML, you define them in Java. So your core beans would be defined in one #Bean-annotated class, and your client configs would subclass that, and override the appropriate beans. This allows you to use standard java #Override annotations, explicitly indicating that a given bean definition is being overridden.

Resources