EJB Priority over same binding name - java

Say I have an EJB with the following configuration:
package com.main.notsimulated
#Singleton
#EJB(name = "java:/sample/MainOne", beanInterface = MainOne.class)
public class MainOne {}
This ejb needs to be present for some other deployables to work. However, using this MainOne modue is not very feasable for me in a testing env. Instead, I would rather inject my own custom version at runtime.
package com.main.simulated
#Singleton
#EJB(name = "java:/sample/MainOne", beanInterface = MainOne.class)
public class MainOne {}
(Note, these are two different jar files)
Hence, my idea here is, let's try to replace the currently deployed with a custom version on the fly. The reason I want to do this is because I do not want to change the nonsimulated version at all, nor effect the consumers of the ejb in any way. i.e All that the consumer currently does is look for that particular jndi name, and performs an indejection and a casting to a particular interface.
I have looked at this post in hopes of figuring out if my MainOne Class from com.main.simulated can evict the currently instantiated MainOne class. However, the the selected answer states it is not programatically possible to start or stop an ejb. I have also looked at this post, but this is more of a practical guide as to how we can inject these beans inour calls.
Hence, my question is, can my latter implementation (com.main.simulated) somehow "replace" the other bean, and ensure the com.main.notsimulated version is never executed?

Deploying two classes, with the same binding is obviously not possible. When trying to do so, one will get a binding exception. However, contrary to my original research, programatically binding a bean is entirely possible. Hence, the solution as to how one can "hijack" an old binding, and replace it with the new is as follows: (Note, replace the class names with what you need)
package com.main.simulated
#Startup
#Singleton
public class MainOne {
#PostConstruct
private void rebindClass() throws NamingException {
final Context context = new InitialContext();
context.rebind("java:/sample/MainOne", this);
}
// other methods that will be called
}
Three important things about this class are: Removal of the #EJB annotation, the #Startup annotation and the rebind of context. The #Startup ensures the #PostConstruct method gets called when our container loads our class. When this happens, the method rebinds a class for a value. Hence, this is the hijack location.
Hope this helps someone.

Related

Inheritance with SqsListener

I have a strange situation that I don't understand.
I would like to decide in a bean, should I enable or disable the SQS listener.
So I've created a config class with a definition:
#Bean
MyListener createListener(Features f){
return f.shouldListen() ? new RealListener() : new MockListener();
}
As you can see, I have such an inheritance:
interface MyListener{}
class RealListener implements MyListener{
#SqsListener(...)
list handleMessage(SqsMessage message){
...
}
}
class MockListener implements MyListener{}
Now, the funny part:
It sometimes works.
After few restarts of the application, the handleMessage() method is called but in most cases it isn't without any exception. The queue is created, all permissions are in place.
To make it working I need to return RealListener from createListener() method or move #SqsListener annotation to a method in the MyListener interface. Both are not options for me, because I don't want to call AWS, when the mock is enabled.
I've tried with conditional bean creation but as Features depends on a DB (indirect entityManager dependency, to be more precise), I can't make it working. I've tried with abstract class instead of interface, but without luck. I've tried to register the RealListener bean in the BeanFactoryPostProcessor but this also doesn't work (same entityManager dependency issue). I've tried to move the annotation to the interface and use #ConditionalOnBean with #Primary to create an empty AmazonSqsClient when the mock is enabled, but it doesn't work.
I could understand that it doesn't work, because the bean has to be created for a type with the method annotated with #SqsListener (not with it's supperclass/interface type), but I have three such beans and a lottery - sometimes all work, sometimes one or two but sometimes none of those.
Do you have any suggestions?
Well... I've found the issue but it still would be nice, to know, what has happened.
So... There is a class QueueMessageHandler using detectHandlerMethods(...) method from the superclass AbstractMethodMessageHandler. This method uses MethodIntrospector.selectMethods() to select methods to scan. This class takes into consideration methods annotated with #SqsListener when there is #EnableSqs in some configuration class.
The problem is, in my project the #EnableSqs annotation is located in some file - not the file with createListener(...) method and not the main class of the Spring Boot application. That means, the class with #EnableSqs can be loaded before or after MethodIntrospector.selectMethods().
The output is:
I have no idea, why it works fine without inheritance and doesn't work with inheritance
To fix the issue, I've moved #EnableSqs to the main class of the project

Lookup for EJB subclass by superclass EJB name

I have a parent and child EJB
#Stateless
#Local(MyCoreLocal.class)
#Remote(MyCore.class)
public class MyCoreEjb implements MyCoreLocal, MyCore {
...
}
#Stateless
#Local(MyCustomizationLocal.class)
#Remote(MyCustomization.class)
public class MyCustomizationEjb extends MyCoreEjb implements MyCustomizationLocal, MyCustomization{
...
}
for architecural reasons at my company, I can't change MyCore project. But both it's all packed together in the same jar and deployed to JBOSS 4.2.3.
The problem is, I have to use MyCustomizationEjb whenever someone calls for MyCoreEjb. How can I override the JNDI entry for MyCoreEjb to point to MyCustomizationEjb in order to redirect all calls for MyCoreEjb transparently to MyCustomizationEjb?
ps: I have full control over ejb-jar.xml of the project, but can't change annotations.
I figured out a way how i could overpass the problem. In reality i didn't need to redirect all call for MyCustomizationEjb. I needed it just for a particular method (at this time).
So my solution was to make a Method Interceptor on the specific method I wanted and just "redirect" the execution to MyCustomizationEjb like this:
public class SpecificMethodInterceptor{
#EJB
MyCustomization myCustomization;
#AroundInvoke
public Object intercept(InvocationContext ctx) throws Exception {
Object result = myCustomization.specificMethod((Param1Type)ctx.getParameters()[0], (Param2Type) ctx.getParameters()[1]);
return result;
}
This way I could now call the extended specificMethod transparently.
I know this is not the most maintainable or scalable solution (since I'll need one interceptor for each method I want to override), but giving this particular project limitations I believe it was the best choice.
Note: There is no problem for not continue the execution (with ctx.proceed()) because this Interceptor is the last one called before the execution reaches the EJB. The only way it could go wrong is if someone make a method interceptor at the EJB, which would be skipped in the execution. But it's not a problem in this particular project.

How to create a bean by type in Spring?

In my ApplicationContext I have several Beans being created the same style. So I have a lot of dublicated code writing a FactoryBean for each of this beans. Those beans have a common ground, implementing all one special interface.
I would like to move all that bean creation to one factory. That one would have to provide a methode like this
<T extends CommonInterface> T createInstance(Class<T> clazz);
There I could implement all the instantiation necessary to create one of my special beans.
My implementation would be called by spring for
#Autowired
private MyCommonInterfaceImplementation impl;
in that way
createInstance(MyCommonInterfaceImplementation.class)
So far I looked at BeanFactory and FactoryBean, both seem not to be I'm searching for.
Any suggestions?
why not use #bean
#Bean
public MyCommonInterfaceImplementation getMyCommonInterfaceImplementation(){
return MyBeanFactory.createInstance(MyCommonInterfaceImplementation.class);
}
//should autowire here
#Autowired
private MyCommonInterfaceImplementation impl;
Basically you need the #Bean annotation on a "factory" only if you need some special handling during the creation of a bean.
If everything can be #Autowired, either by setters, fields, or one constructor, and nothing else needs to be done on a bean during initialization, you can simply declare the annotation #Component on each implementation of your interface. This works as long as you have component scanning active inside your application. The result will be that for each component spring will create a bean which you can use.
I'm writing this on a mobile so showing code is not the best. Just follow some tutorial on #ComponentScan, or if you need, let me know and I can augment this answer with an example.
As of Spring 4.3 you no longer have to annotate your bean classes and you can let them be instantiated via a componentscan.
#Configuration
#ComponentScan(
value = "some.package.path",
includeFilters = {
#Filter(type = ASSIGNABLE_TYPE, value = {
MyClass1.class,
MyClass2.class,
MyClass3.class
})
})
This actually creates beans for the three classes listed there. The example should work without filters as well (everything in the package becomes a bean). This works as long as the classes have a single constructor that can be used for autowiring. I don't think it is possible to filter for all implementations of a particular interface and then register a bean.
To do that, you might do something with a ContextListener and e.g. use reflection to find out what classes to instantiate and then use context.autowire(..) to inject any dependencies from your context. A bit hacky but it might work.
#Override
public void onApplicationEvent(ContextRefreshedEvent event) {
ApplicationContext context = event.getApplicationContext();
MyClass bean
= context
.getAutowireCapableBeanFactory()
.autowire(MyClass.class, Autowire.BY_NAME.value(), true);
...
}
That still leaves the problem of how to get the bean registered in the context of course.
You might also be able to adapt the answer to this SO question on how to add beans programmatically.
Finally the best approach I've found is using a ConfigurationClassPostProcessor. As example I've used https://github.com/rinoto/spring-auto-mock
But, since it is quite complicated and "too much magic" to create beans from nothing, we decided to explicitly create those beans via #Bean.
Thanks for your answers.

Ejb returns java.lang.NullPointerException

I am newbie in cdi and these are my first steps.
I have a bean in ejb module:
#Stateless
public class TestBean {
public String getIt(){
return "test";
}
}
I have a POJO in war module (I tried with #EJB and #Inject - same result)
public class SaveAction extends Action{
#EJB
private TestBean bean;
#Override
public void execute(){
....
String test = bean.getIt(); //HERE I GET java.lang.NullPointerException
...
}
}
Both war and ejb are inside ear. In log I see
EJB5181:Portable JNDI names for EJB TestBean:
[java:global/example.com/my-ejb/TestBean!com.example.TestBean,
java:global/example.com/my-ejb/TestBean]]]
From that I conclude that bean is initialized - but I can't find it. What am I doing wrong?
CDI and other dependency injection containers don't use magic! It's just ordinary java code that cannot do more or less than any other java code written anywhere. So it is impossible for a framework to do injection when an object is instantiated directly via new:
SaveAction action = new SaveAction();
// don't expect any injection has happened - it can't! no magic!
// action.bean is still null here!
The framework does not have any idea that an object like SaveAction has been instantiated. (Therefore it would be necessary to somehow inform the framework about the newly created object - but neither the constructor nor the 'new' statement do this! Just think one minute about how you would write such a framework code! It's not possible!* ).
To make injection work, the object must be created by the container instead! Otherwise it is NOT managed! (See also chapter 3.7 of the Web Beans specification (JSR 299)).
The best way to do this is to let the container inject the object into another already managed bean. It seems this just deferes the problem, but there are some already managed beans in your application, like the servlet!
Suggestion: Make your SaveAction CDI aware (e.g. annotate it with #Default) and let it be injected into your servlet!
Tutorials:
http://middlewaremagic.com/jboss/?p=1063
http://hudson.jboss.org/jenkins/job/JBoss-AS7-Docs/lastSuccessfulBuild/artifact/guides/developer-getting-started-guide/target/docbook/publish/en-US/html/helloworld.html
*) In theory it should be possible using aspect oriented programming or instrumentation to manipulate the constructors of beans to notify the container if they are invoked. But that's a very complex concept with many unsolved issues I think.

Spring #Value annotation always evaluating as null?

So, I have a simple properties file with the following entries:
my.value=123
another.value=hello world
This properties file is being loaded using a PropertyPlaceHolderConfigurer, which references the properties file above.
I have the following class, for which I'm trying to load these properties in to like so:
public class Config
{
#Value("${my.value}")
private String mValue;
#Value("${another.value}")
private String mAnotherValue;
// More below...
}
The problem is that, mValue and mAnotherValue are ALWAYS null... yet in my Controllers, the value is being loaded just fine. What gives?
If instances of Config are being instantiated manually via new, then Spring isn't getting involved, and so the annotations will be ignored.
If you can't change your code to make Spring instantiate the bean (maybe using a prototype-scoped bean), then the other option is to use Spring's load-time classloader weaving functionality (see docs). This is some low-level AOP which allows you to instantiate objects as you normally would, but Spring will pass them through the application context to get them wired up, configured, initialized, etc.
It doesn't work on all platforms, though, so read the above documentation link to see if it'll work for you.
I had similar issues but was a newbie to Spring.
I was trying to load properties into an #Service, and tried to use #Value to retrieve the property value with...
#Autowired
public #Value("#{myProperties['myValue']}") String myValue;
I spend a whole day trying various combinations of annotations, but it always returned null.
In the end the answer as always is obvious after the fact.
1) make sure Spring is scanning your class for annotations by including the package hierachy
In your servlet.xml (it will scan everything below the base value you insert.
2) Make sure you are NOT 'new'ing the class that you just told Spring to look at. Instead, you use #Autowire in the #Controller class.
Everything in Spring is a Singleton, and what was happening was Spring loaded the values into its Singleton, then I had 'new'ed another instance of the class which did not contain the newly loaded values so it was always null.
Instead in the #Controller use...
#Autowired
private MyService service;
Debugging...
One thing I did to find this was to extend my Service as follows...
#Service
public class MyService implements InitializingBean
Then put in debug statements in...
#Override
public void afterPropertiesSet() throws Exception {
// TODO Auto-generated method stub
LOGGER.debug("property myValue:" + myValue);
}
Here I could see the value being set on initialization, and later when I printed it in a method it was null, so this was a good clue for me that it was not the same instance.
Another clue to this error was that Tomcat complained of Timeouts trying to read from the Socket with Unable to parse HTTPheader... This was because Spring had created an instance of the service and so had I, so my one was doing the real work, and Spring was timing out on its instance.
See my answer here.
I ran into the same symptoms (#Value-annotated fields being null) but with a different underlying issue:
import com.google.api.client.util.Value;
Ensure that you are importing the correct #Value annotation class! Especially with the convenience of IDEs nowadays, this is a VERY easy mistake to make (I am using IntelliJ, and if you auto-import too quickly without reading WHAT you are auto-importing, you might waste a few hours like I did).
The correct import is:
org.springframework.beans.factory.annotation.Value
As its working with #Controller, it seems you are instantiating Config yourself. Let the Spring instantiate it.
You can also make your properties private, make sure your class is a Spring bean using #Service or #Component annotations so it always gets instantiated and finally add setter methods annotated with #Value . This ensures your properties will be assigned the values specified in your application.properties or yml config files.
#Service
public class Config {
private static String myProperty;
private static String myOtherProperty;
#Value("${my.value}")
public void setMyProperty(String myValue) {
this.myProperty = myValue;}
#Value("${other.value}")
public void setMyOtherProperty(String otherValue) {
this.myOtherProperty = otherValue;}
//rest of your code...
}
Add <context:spring-configured /> to you application context file.
Then add the #Configurable annotation to Config class.
In my case in my unit test, executeScenarioRequest always is null
#RunWith(SpringRunner.class)
#ExtendWith(MockitoExtension.class)
class ScenarioServiceTestOld {
#Value("classpath:scenario/SampleScenario.json")
Resource executeScenarioRequest;
Change #ExtendWith(MockitoExtension.class) to #ExtendWith(SpringExtension.class)

Categories

Resources