HttpServlet lifecycle and serialization - serialization

I wonder if the init method of a HttpServlet is called after deserialization.
I don't know if any container ever serializes a servlet but it implements the Serializable interface so there is a possibility to do that.
The JavaDoc for the init method points out: "Called by the servlet container to indicate to a servlet that the servlet is being placed into service."
Is a deserialization equals "placed into service" ?

While I have never actually dealt with a container that would swap out a servlet by serializing it, and I honestly can't really imagine when a modern container would do this, but I have always understood that init() is called exactly once for the servlet in its lifecycle, so, it would not be called again on deserialization. As with anything Serializable you would need to write special handling by implementing readFields().

Related

what is the purpose of #Context and #Parallel annotation

I have few beans which needs to be initialized either parallely or eagerly and to do this while reading the docs of micronaut, I noticed #Parallel annotation which can be used to initialize beans parallely and I came across #Context annotation which I am not able to understand clearly.
As for as my understanding is concerned, #Parallel annotation will shutdown the application if any of the beans executing simultaneously fails whereas #Context will not even startup the application if there is any failure.
I just wanted to check if this correct? Also, if I want to do eager initialization of bean rather than on-demand which annotation is the best one to use?
Any help appreciated, thanks in advance!
When you annotate a bean using the Context annotation, it simply means that the bean gets initialised earlier and eagerly (with the Application Context) than beans annotated with e.g. Singleton or Prototype.
Context scope indicates that the bean will be created at the same time as the ApplicationContext (eager initialisation)
With these annotations you define the scope of your bean within the application context.
Parallel does not define a bean scope, but as you found out yourself behaves accordingly to Context.
As a rule of thumb: If you have beans that need to start early, with the application context, annotate them using #Context.
If you have a singleton bean with a slow startup path declare it with #Singleton and #Parallel.
This is how I understud the documentation.

Different between CGLIB proxy and JDK proxy on Spring AOP perspective

Baeldung has this section:
this limits matching to join points where the bean reference is an
instance of the given type, while target limits matching to join
points where the target object is an instance of the given type. The
former works when Spring AOP creates a CGLIB-based proxy, and the
latter is used when a JDK-based proxy is created. Suppose that the
target class implements an interface:
public class FooDao implements BarDao {
...
}
In this case, Spring AOP will use the JDK-based proxy, and we should
use the target PCD because the proxied object will be an instance of
the Proxy class and implement the BarDao interface:
#Pointcut("target(com.baeldung.pointcutadvice.dao.BarDao)")
On the other hand, if FooDao doesn't implement any interface, or the
proxyTargetClass property is set to true, then the proxied object will
be a subclass of FooDao and we can use the this PCD:
#Pointcut("this(com.baeldung.pointcutadvice.dao.FooDao)")
I'm still confuse why this just works with CGLIB proxy and target just works with JDK proxy. Could you help to tell me the different between them?
Actually, the explanation in the tutorial does not make much sense:
Both this(MyInterface) and target(MyInterface) work for JDK proxies, if the bean is declared as a MyInterface type.
Both this(MyClass) and target(MyClass) work for CGLIB proxies, if the bean is declared as a MyClass type.
Just try, and you will see that I am right. In Spring AOP, there is not real difference between this() and target(), because due to its proxy-based nature, it implicitly only supports execution() pointcuts from AspectJ.
In native AspectJ however, you also have other pointcut types such as call(), and there you would see a difference: this() would match the caller's type, while target() would match the callee's type. E.g., if you intercept a method A.a() calling B.b() via pointcut call(B.b()), this() would return an A instance, while target() would return a B instance. Do not worry, if this is difficult to understand for you, because for Spring AOP and execution pointcuts it really does not matter.
The only subtle difference I noticed in Spring AOP is, that for MyInterfaceImpl implements MyInterface, pointcut target(MyInterfaceImpl) would actually match, while this(MyInterfaceImpl) would not. This is because for JDK proxies, the proxy actually extends java.lang.reflect.Proxy, not MyInterfaceImpl. The proxy only delegates to a MyInterfaceImpl instance.
Edit: If you keep in mind that, in contrast to native AspectJ which involves no dynamic proxies, the semantics in Spring AOP are such that
this() relates to the proxy object, while
target() relates to the proxied object (proxy target),
it becomes clear why in this special case for JDK proxies target() matches, but this() does not.
Reference: Spring manual, section "Declaring a pointcut - examples":
this(com.xyz.service.AccountService): Any join point (method execution only in Spring AOP) where the proxy implements the AccountService interface.
target(com.xyz.service.AccountService): Any join point (method execution only in Spring AOP) where the target object implements the AccountService interface.
Only in this case, we are not asking for the interface class (which both the proxy and the target object implement), but for the implementation class itself.
Bottom line: For all intents and purposes, in normal use cases you can use either this() or target() for both JDK and CGLIB proxies. I recommend to stick with target(), because it best matches the implicit execution() semantics of Spring AOP, and usually you are interested in information about the target rather than about the proxy..

Can i make my own Singleton Stateless Bean with EJB 3.0?

Now, with EJB 3.1, we can find the javax.ejb.Singleton annocation that can ensure that this bean is going to be singleton.
Is there a way that i can ensure singleton using stateless beans in EJB 3.0 with some modifications in my code (use of the keyword static, or other way to do that....)
If you're able to limit your #Stateless bean pool size to exactly 1, then you can get pretty close to an #Singleton.
The effect would be like having an #Singleton that uses #Lock(WRITE) for all calls (i.e. no concurrency) and does not eagerly startup via #Startup (it will start on first access).
You might still be able to get the effect of #Startup if your platform has the option to eagerly fill #Stateless bean pools.
Is there a way that I can ensure singleton using stateless beans in EJB 3.0 with some modifications in my code (use of the keyword static, or other way to do that....)
No, nothing standard. Your container might provide some specific extensions though (e.g. JBoss has a proprietary #Service annotation).

Composition of Objects

I have a class that acts as a manager and does some work.
A servlet that starts up when the application server starts up instantiates this manager.
I need to add another class that will do other work, and needs to coordinate with the manager.
I was thinking about adding the class to the manager as an instance variable.
Should I have the manager instantiate the new class (like in the constructor), or have the servlet instantiate the new class and call manager.setNewClass() after the manager has been instantiated?
Well, as a gross-over-generalization, you should instantiate it in the servlet and pass it into the manager (either via a constructor parameter, or via setNewClass())... Inject the dependencies rather than hard-code them.
However, depending on your exact use-case, even that might not be the right answer. You might be better off with a Builder for constructing the manager class. That way, the builder manages the construction of the entire manager (including any dependencies) rather than hard-coding it into the servlet. This would move the dependency out of the servlet and into the builder (which you can better deal with in tests and other code).
The short answer is that there's no silver bullet. Without knowing the hard relationships between all of the classes, and the roles and responsibilities, it's hard to say the best method. But instantiating in a constructor is almost never a good idea and you should inject the dependency in some form or another (but from where is up for debate)...
This reminds me of the FFF pattern.
It does not matter where you create the instance. Just create wherever it fits you best, and if you need it somewhere else, just apply some basic refactoring.
If you really need decoupling try using some tool like Guice, but only if you really need it.
You should do the latter -- it decouples the manager from its delegate. To do the decoupling correctly, you should create an interface that defines the behavior the manager expects, and then provide an implementation via inversion of control/dependency injection. This will allow you to test the manager and its worker class (I called it a delegate, but it might not be) in isolation.
EDIT -- this answer assumes java because you mentioned servlet.
You have your manager class, in it you expect an interface
class Manager {
Worker worker;
Manager(Worker worker) {
this.worker = workder
}
}
Worker is an interface. It defines behavour but not implementation
interface Worker {
public void doesSomething(); //method definition but no implementation
}
you now need to create an implementation
class WorkerImpl implements Worker {
// must define a doesSomething() implementation
}
The manager just knows it gets some Worker. You can provide any class that implements the interface. This is decoupling -- the Manager is not bound to any particular implementation, it is bound only to the behavour of a worker.

Dependency Inject with Ninject 2.0

A little question regarding Ninject.
I use a WCF 'duplex channel' to communicate with a service. The channel is defined as an interface, lets call it IMyChannel for simplicity. To instantiate a channel we use DuplexChannelFactory<IMyChannel> object's CreateChannel() method.
So far I have manage to bind the factory class with this.
Bind< DuplexChannelFactory< IMyChannel>>().ToMethod(context =>
new DuplexChannelFactory< IMyChannel>(
new MessageEndPoint(),
new NetTcpBinding(),
"net.tcp://localhost:8321")).InSingletonScope();
}
}
However I'm a little unsure how to bind the IMyChannel interface since I use Ninject to create DuplexChannelFactory<IMyChannel> so to bind IMyChannel I do Bind< IMyChannel>(). ???
This isnt really an IOC container issue.
While, in theory, you could do:
Bind<Func<IMyInterface>>().ToConstant( context => context.Kernel.Get<DCF<IMC>>().CreateChannel)
and then demand a Func<IMyInterface>() in your ctor, calling it whenever you want to create a channel.
The problem is that the object that CreateChannel() returns implements both IMyChannel and IDisposable, hence you cannot neatly use a using block around it if that's what you're going to return. This is what the tooling generates for you when you create Service Reference, and WCF OOTB doesnt offer a general mechanism here.
I personally inject a factory, and have it have a Create<T>() method that yields a wrapper object that:
implements IDisposable
has a way to call methods across the channel.
It's not injectable into a post so hopefully someone will be along soon with a nice wrapper class of this nature.
Not sure if Singleton is appropriate, but I'd have to look around to be sure.