Can we access/call Stateless Session Bean from Static method? - java

I am injecting a Stateless session bean in a class that has many static methods.
I would like to access this bean from these Static method. There is no documentation on this one.
So I wondering if its allowed. If yes, any downsides? Recommended / not recommended?

If its allowed? Yes, it can be allowed within container and outside of container.
You can access a EJB from non-EJB. Please check below link.
https://stackoverflow.com/a/9061924/1718893
If the class and EJB are in same project/deployable, then JNDI call should be easy. Few steps mentioned in above link can be skipped.
Recommended in scenario like below -
Depending on scenario, this can be a recommended approach. I came across this situation when I had to implement factory pattern. The EJBs were called only when required and based on conditions. I could have made Factory class itself a EJB. But due to its dependencies on some other decision making components, that was not possible.
Not recommended in scenraio like below -
Depending on how much disciplined development is followed, such approach can be discouraged as well. If all the developers are not much experienced with EJBs, its transaction management and deployment, then down the line, this approach can create dangerous situations.

You can definitely access static method or variables from an instance method or variable... but can not access an instance method or variable from a static method!

Related

Advantages and disadvantages of using one of Singleton or Dependency Injection over the other

I know the simple differences between them, but when it come to the scenario where I want to share an object instance in the app, I can done this by using DI or Singleton.
when this question come to my mind I became confused, since I can use both, I think that one of them must be better than the other in cases like multi-threading or memory management JVM or code maintainability ...
can someone tell me what is the advantages and disadvantages of using one of them over the other in the above scenario and what is the correct choice ?
Firstly, Both DI and Singleton are Design-patterns.
Dependency injection:
DI is a way of injecting dependent objects into your application.
Singleton pattern:
Create one and only instance of an object.
Source:Design patterns-Singleton
can someone tell me what is the advantages and disadvantages of using one of them over the other in the above scenario and what is the correct choose ??
DI takes care of object creation, configuration and injection. That means DI can create, configure and inject a Singleton object too. DI is helpful when you want to make object creation externalised, loosely coupled and easily maintainable.
Singleton provides only one instance of the object and where you can access the object globally. This object can be injected into the application by DI also. This is helpful when you want only one object, lazy initialisation (creation on first use) and global access are needed.
Singleton in the design pattern that states only one instance per jvm can be created (if implemented correctly).
DI(Dependency injection) is the design pattern that takes responsibility injecting dependency(inversion of control). Dependency can be singleton/prototype/scoped ... etc. Other than injecting dependency, DI patterns like spring DI also controlls lifecycle of bean.

JAX-RS Resource Lifecycle Performance Impact

I know by default JAX-RS endpoints lifecycle is once-per-request, so that the request specific informations can be injected into the instance.
And we can also make an endpoints Singleton meaning once-per-application, in which the request specific informations cannot be injected into the instance rather it can be injected into the requested method.
1. So i would like to know which approach is better in terms of performance, either once-per-request or once-per-application.
2. I would also like to know the pros and cons of these approaches other the injecting request specific informations
3. Which approach you prefer to use in your API applications
Note: i have been using the once-per-request approach so far, but i always wonder is that is efficient, definitely its make coding easier and reusable.
To start with your last question: I'm always using the default (per-request) and I seldom came to a point where I wanted to change this.
What might be a reason to prefer one over the other?
If you want to serve some static content (maybe a welcome-document of your API) it makes sense to produce this content only once and hold it in a singleton resource class. But you can achieve the same by e.g. injecting an #ApplicationScoped CDI bean in a per-request scoped resource class.
If you prefer injecting the #xxxParam values like #QueryParam as fields instead of method parameters you should use the per-request lifecycle. This is not supported for singletons. (This does not include injecting via #Context).
I made a little test to compare the performance of both. You can find the sources and the results on github. In short: I measured a difference from about 1.5 %. I don't think this should affect your application too much.
Comparing the results of the JVisualVM monitoring I would tend to say that the per-request test is using more memory but you should decide on your own if this really affects your application.

How to maintain a centralized Object across the application

I am developing an application where I need to create an object and multiple classes have to access and modify that object. How to see the recent changes made by the other class object and how to access the object centrally through all the classes with out passing that object as a parameter across all the classes?
I am creating an Apache POI document where I am adding multiple tables, multiple headers/footers and paragraphs. I want only a single XWPFDocument object present in my application.
Is there any design pattern we can achieve this?
Well the singleton design pattern would work - but isn't terribly clean; you end up with global static state which is hard to keep track of and hard to test. It's often considered an anti-pattern these days. There are a very few cases where it still makes sense, but I try to avoid it.
A better approach would be to use dependency injection: make each class which needs one of these objects declare a constructor parameter of that type (or possibly have a settable property). Each class shouldn't care too much about how shared or otherwise the object is (beyond being aware that it can be shared). Then it's up to the code which initializes the application to decide which objects should be shared.
There are various dependency injection frameworks available for Java, including Guice and Spring. The idea of these frameworks is to automatically wire up all the dependencies in your application, given appropriate configuration.
There is Singleton Pattern for this, it creates a single instance for the application and is shared without passing around.
But it not not the best of options.
Why is it a bad option?
It is not good for testability of code
Not extensible in design
Better than Singleton Pattern is an application wide single instance
Create a single object for the application and share it using some context object. More on this is explained by Misko in his guide to testable code
single instance and not Singleton Pattern
It stands for an application wide single instance, which DOES NOT inforce its singletonness through a static instance field.
Why are Singletons hard to test?
Static access prevents collaborating with a subclass or wrapped version of another class. By hard-coding the dependency, we lose the power and flexibility of polymorphism.
-Every test using global state needs it to start in an expected state, or the test will fail. But another object might have mutated that global state in a previous test.
Global state often prevents tests from being able to run in parallel, which forces test suites to run slower.
If you add a new test (which doesn’t clean up global state) and it runs in the middle of the suite, another test may fail that runs after it.
Singletons enforcing their own “Singletonness” end up cheating.
You’ll often see mutator methods such as reset() or setForTest(…) on so-called singletons, because you’ll need to change the instance during tests. If you forget to reset the Singleton after a test, a later use will use the stale underlying instance and may fail in a way that’s difficult to debug.

are IoC containers singletons or static?

I'd like to better understand how IoC containers work and code up something to use for myself. Is there a best practice when creating the class for the container? Is it a singleton? is it static? Is it not a singleton but just has a bunch of static properties to hold resolved objects?
The IoC containers I know of are neither static nor singletons and I can't see any good reasons to make them. Just make it a normal class and create instances of it. There are scenarios where you might want to use several instances to separate independent concerns.
As you want to keep your components agnostic of the container, i.e. don't make them reference the container. If your component (the object which is being resolved by the container) needs to be able to access the container to get new instances, you would usually abstract an interface for this (commonly referred to as Service Locator Pattern (.NET, but it's all the same)), and let the container inject itself into the component. Again, no reason for static classes or methods.
One very good reason to follow this practice is that you are able to exchange the container implementation, for example switch to a 'professional' IoC framework, without touching your components at all.
Apart from that, there are a number of restrictions for static classes and methods in general, which you usually don't want, especially not when your system is likely to be changed, to grow and to get complex. To mention two: Static classes can't implement interfaces. Consequently you can never mock your container for testing purposes; Every usage of the container requires a fixed reference to the container assembly rather than to a contract. You cant subclass a static class;

Guice design patterns: Any advantages to requiring explicit bindings?

I am relatively new to Guice, so this may be basic question. It looks like Guice has the option to require explicit bindings. Is there any clear advantage to requiring explicit bindings? Does anyone regularly use this option in practice?
We use this option in practice. We use Guice only to wire our application together, not for any sort of per-request object construction. As a result, most of our bindings are in Singleton scope - we want, for example, our business logic and statistics interfaces to both work off the same persistence layer object.
In the absence of an explicit binding, Guice will attempt to satisfy the injection point using a JIT binding. This binding will be done in the "no scope" scope, which provides a fresh object instance to each injection point. That's almost never what we want, and leads to bizarre runtime errors. Forcing explicit bindings forces people to think about, and enumerate, the scope of each of their bindings.
I recently sat through a 1-hour debugging session because we didn't use this config. The problem was that multiple instances were created when I expected a singleton by default. Forcing an explicit binding is a good reminder to think about whether it should be a singleton or not.
I too spent few hours in debugging. The reason was that I forgot to add a binding of a concrete class to singleton scope. In order to have explicit bindings always, I used one answer from How do you prevent Guice from injecting a class not bound in the Module? (not the current chosen one): binder().requireExplicitBindings(); (in the configure method of AbstractModule).

Categories