How to control object's lifecycle with Guice - java

I have Guice-injected objects which have two lifecycle methods bind() and unbind(). The method bind() is called automatically after the object is instantiated by Guice using following annotated method:
#Inject
final void autoBind() {
bind();
}
What I want to do is to call the method unbind() on the old (current) object before a new instance of the object is created by Guice. How do I do that?
Thanks in advance!

First of all, I would not advise that you just annotate arbitrary methods with #Inject. Keep it to constructors, and occasionally for optional injection and/or field injection.
What you are trying to do does sound a bit weird, and I'm not sure it's exactly what you want. Can you please provide more background on what you're trying to do because maybe a different approach is better. There are definitely some concerns here with thread safety and how you manage references.
Based on what you described, an approach like what #meverett mentioned would probably work. If the objects you have are Foos, it would look something like this.
// Later on be sure to bind(Foo.class).toProvider(FooProvider.class);
final class FooProvider implements Provider<Foo> {
private final Provider<Foo> unboundFooProvider;
private Foo currentInstance;
#Inject FooProvider(#Unbound Provider<Foo> unboundFooProvider) {
this.unboundFooProvider = unboundFooProvider;
}
#Override public Foo get() {
if (currentInstance != null) {
currentInstance.unbind();
}
currentInstance = unboundFooProvider.get();
currentInstance.bind();
return currentInstance;
}
}
NOTE that your #Unbound Foo provider would generate Foos without invoking any special methods. The regular FooProvider keeps track of state and deciding when to bind() and unbind() the instances. Please be careful with how you manage multiple instances and use them with multiple threads.
Also, just to be clear: I'm using #Unbound since the methods you want to invoke are called bind() and unbind(). I'm not using "bound" in the Guice sense.
Also note... off the top of my head I'm pretty sure Providers are treated as singletons, so maintaining state like this will work. If it didn't, you could obviously just create a level of indirection with some kind of singleton factory (but that shouldn't be necessary).

Previous responses address other concerns nicely, so to just answer the question:
Netflix introduced governator in github in 2012 to "enhance Google Guice to provide ... lifecycle management". It provides annotations (#PreConfiguration, #PostConstruct, #PreDestroy, and others), classpath scanning & auto binding, and other features. Bootstrapping is straight forward.

I suppose you could have a provider that keeps a reference to the current object. When you call get on the provider it would unbind the last object, construct the new one and save the reference to it.
though I'm not really sure why you would want to do something like this since other objects can in theory still be referencing it

Related

How can find an instance of class at runtime in Java?

Suppose I have a class with an annotation, e.g.:
#MyConfig
class MyConfiguration {
#MyParameter
String parameter;
}
If I know an instance of this class exists (for instance, one was constructed in another thread) how can I get a reference to the instance elsewhere. I'm trying to find the instance by its #Annotation.
You cannot simply conjure up a reference to an object based on its type or annotations, nor should you really want to. The primary reason for this is garbage collection - the JVM cleans up memory for you as objects fall out of scope; if you could create new references dynamically, the garbage collector would not be able to safely clean anything up, and you'd rapidly run out of memory.
That said there's many ways you can build up functionality like you're describing pretty simply, so that you can look up an object by its type.
The easiest (and arguably best) way to do this is to simply register the instance you want, using a Map (consider Guava's ClassToInstanceMap). While you have to explicitly add to the map, that is actually going to be a lot cleaner for you in terms of code-compartmentalization. Even if you make the caching behavior a static method on the annotation, or something like that, separating construction from caching is a good practice to get into.
// somewhere accessible to both the constructing and accessing code, such as a
// public static field on the Annotation
Map<Class<? extends Annotation>,Object> annotationMap = new HashMap();
// wherever the instance is constructed
annotationMap.put(MyConfig.class, new MyConfiguration());
// wherever the instance is needed
MyConfiguration myConf = (MyConfiguration)annotationMap.get(MyConfig.class);
You've likely noticed that this holds Object values, because any class can theoretically be annotated, so we have to explicitly cast. This will work, assuming you enforce what types are inserted into the map, but it is fragile. Truth be told, the idea of associating annotations with instances is fragile in itself, so this is likely the least of your worries.
If you want to ensure that the most recently constructed MyConfiguration is accessible like this, you could put the above in it's constructor, like so:
#MyConfig
class MyConfiguration {
public MyConfiguration() {
// note this is potentially dangerous, as this isn't finished constructing
// yet so be very cautious of this pattern, even though it might seem cleaner
annotationMap.put(MyConfig.class, this);
}
}
Now you can be confident that, if a MyConfiguration instance exists, it is accessible from annotationMap by its annotated type.
As I hinted above however, I suspect neither of these are good solutions for you. And really the reason why is because annotations are not designed at all to let you refer to instances; they are instead meant to let you know things about an instance once you already have one. So let me ask you, why do you think you need to lookup an object by its annotation? Is there another pattern you can use instead?
I suspect what you're really trying to build is a Singleton - you expect your runtime to have exactly one instance of MyConfiguration, and you want all your code to easily access it. A standard pattern for this is:
#MyConfig
class MyConfiguration {
private static MyConfiguration INSTANCE = null;
public static MyConfiguration getInstance() {
// note this is not thread-safe
// see the above link for several thread-safe modifications
if(INSTANCE == null) {
INSTANCE = new MyConfiguration();
}
return INSTANCE;
}
This lets any code call MyConfiguration.getInstance() and be able to access the instance. That said, Singletons are generally considered bad practice (though less so than what you're describing). Ideally, you should be passing your configuration instance around to whatever classes or threads need it. Passing your references explicitly, rather than relying on a semi-magical cache or global state like a singleton, is far and away the "right" way to deal with the problem you're facing.

Java Annotation and Processor to mark a method as so it can be called once and only once?

I need to be able to mark methods so that they throw a RuntimeException if they are called more than once.
I am trying to enforce some single assignment semantics and the number of parameters to my class is too large to put in a single constructor and I need to be able to make these classes JAXB aware as well, so the objects need to be mutable but I want to enforce single assignment semantics.
I am pretty sure I can do this with Aspects, but I would really like to be able to use my own Annotations processor instead.
I know how to do this with Decorators in Python.
How do I write an Annotation processor that can intercept calls to the annotated method at runtime and not just at compile time?
I think I am on to something with with Dynamic Proxies intercepting the method calls, I just need to figure out how to integrate them with my Annotation processor.
Dynamic Proxies require you to use an Interface, that is way to cumbersome, I have a CGLib MethodInterceptor working now, much less requirements on what gets intercepted and decorated, at the expense of adding a dependency.
Nope, there's nothing ready-to-use. And AspectJ seems the only way to make it work in a more general manner. As JB Nizet noted - the annotation should have a parser to parse it.
However, I would advise for a better and simpler solution - the Builder pattern. What does it look like:
you have a FooBuilder (it may also be a static inner class) which is mutable and has a setter and getter for each of the fields
FooBuilder has a build() method that returns an instance of Foo
Foo has a constructor that takes only FooBuilder, and you assign each field there.
That way:
Foo is immutable, which is your end goal
It is easy to use. You only set the fields that you need. Something like:
Foo foo = new Foo.FooBuilder().setBar(..).setBaz(..).build();
That way the builder can be JAXB-aware. For example:
FooBuilder builder = (FooBuilder) unmarshaller.unmarshal(stream);
Foo foo = builder.build();
JAXB objects need to be mutable, and your requirement is an immutable object. Hence the builder comes handy to bridge that.
This question shows some resemblance with question Applying CGLib Proxy from a Annotation Processor.
If you want to be able to change the behavior of the original source code in an annotation processor have a look at how http://projectlombok.org/ achieves this. The only downside IMO is that lombok relies on com.sun.* classes.
Since I need this kind of stuff myself I wonder if someone knows of a better way to achieve this, still using annotation processors.
You can configure JAXB to use field (instance variable) access using #XmlAccessorType(XmlAccessType.FIELD). This will allow you to do what you need to with the set method:
http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html
You can also use JAXB's XmlAdapter mechanism to support immutable objects:
http://blog.bdoughan.com/2010/12/jaxb-and-immutable-objects.html
Instead of using an annotation you can use.
assert count++ != 0;
You would need one counter per method.
I had a similar requirement. Long story short when you inject components in Spring the cyclic dependency situation like A depends on B and B depends on A is perfectly fine, but you need to inject these components as fields or setters. Constructor injection causes a stack overflow. Therefore I had to introduce a method init() for these components, which unlike constructors might be erroneously called more than once. Needless to say boilerplate code like:
private volatile boolean wasInit = false;
public void init() {
if (wasInit) {
throw new IllegalStateException("Method has already been called");
}
wasInit = true;
logger.fine("ENTRY");
...
}
started to emerge everywhere. Since this is nowhere close to being a critical spot of the application, I made a decision to introduce an elegant thread-safe one-liner solution favoring conciseness over speed:
public class Guard {
private static final Map<String, Object> callersByMethods = new ConcurrentHashMap<String, Object>();
public static void requireCalledOnce(Object source) {
StackTraceElement[] stackTrace = new Throwable().getStackTrace();
String fullClassName = stackTrace[1].getClassName();
String methodName = stackTrace[1].getMethodName();
int lineNumber = stackTrace[1].getLineNumber();
int hashCode = source.hashCode();
// Builds a key using full class name, method name and line number
String key = new StringBuilder().append(fullClassName).append(' ').append(methodName).append(' ').append(lineNumber).toString();
System.out.println(key);
if (callersByMethods.put(key, source) != null) {
throw new IllegalStateException(String.format("%s#%d.%s() was called the second time.", fullClassName, hashCode, methodName));
}
}
}
Now, since I prefer building applications within DI frameworks it might sound natural to declare Guard as a component, then inject it, and call an instance method requireCalledOnce instead. But due to its universal flavor, static reference yields more sense. Now my code looks like this:
private void init() {
Guard.requireCalledOnce(this);
...
}
and here is an exception upon the second invocation of init of the same object:
Exception in thread "main" java.lang.IllegalStateException: my.package.MyComponent#4121506.init() was called the second time.
at my.package.Guard.requireCalledOnce(Guard.java:20)
at my.package.MyComponent.init(MyComponent.java:232)
at my.package.MyComponent.launch(MyComponent.java:238)
at my.package.MyComponent.main(MyComponent.java:48)

Immutability after dependency injection, initialization

I'd like to be able to specify that an object's member variables are immutable once the object has been "initialized", which to me means after it has been injected with any dependencies, and has performed any other initialization operations that it can only perform after DI.
Are there languages that satisfy my interest - that formalize DI, initialization, and support immutability in this fashion? Maybe it's dumb to make them a part of a language; maybe not. I'm not sure.
Today I program in Java, but I can't use "final" nearly as much as I'd like, because those phases happen after the constructor has finished execution. Any advice on how to get what I want with Java? I guess I could have my objects implement a base class so that those phases happen before the constructor finishes, or use aspects to do the same.
Thoughts?
There are two main ways of producing immutable objects:
use the builder/factory pattern - the builder may be mutable, but the objects it creates are immutable, usually implemented with final fields. You can also combine the two, so the object itself is used to build new instances, usually via "mutator" methods that change state on a separate, new instance. Spring's FactoryBean is an example of this.
create a MutableObject subclass, which maintains a flag for mutable state. All your mutators check the mutable state before making any changes - if the object has been set to immutable, then the check throws an exception, otherwise the change goes ahead.
The first approach is quite Spring-centric, since it requires implmentation of a spring-specific interface. You can create factory beans that are regular beans, via factory-method/factory-bean attributes on a bean, which removes the spring dependency from your code.
Using the second approach is particularly useful with spring. You can instruct spring to call a method after bean initialization, e.g. seal() which seals the object - makes it immutable. Alternatively, you can implement a small BeanFactoryPostProcessor to do this automatically without having to remember to set the init-method="seal". on each immutable bean.
I guess it depends on what you want out of the immutability. If you want the guaranteed thread safety (where everything must be declared final, including the dependencies) then I think factory, builder or constructor injection are your only options.
If however you just want immutability of state, then declaring the state variables final should be enough. Even the immutable String class has a mutable field in its implementation (a cache of the hashcode value). As long as your code otherwise ensures that an instance is not available without injection, all should be well.
In Java, you can use a builder to initialize an immutable object in its constructor, so you'd shy away from setters.
If you use Scala, though, immutability is the default.
In Java, if you're using mutator methods to do your setting anyhow, it's pretty cheap (though also pretty ugly in my eyes) to add logic to prevent alterations once the object is initialized.
public void setMyProperty(String newValue) {
checkInitialized();
myProperty = newValue;
}
public void checkInitialized() {
if ( initialized ) {
throw new IllegalStateException("Setter called after initialization");
}
}
At best though this is giving a dynamic check. It doesn't give you any static feedback over what you would have already had.
To specify that a class is immutable, you can use the #Immutable annotation.
You can see the Javadoc here.
This works well with the Findbugs plugin in Eclipse.
#Alexander:
As I understand him, he asked how to specify that a class is immutable. Not how to write an immutable class. This annotation can give you tool support to verify that you don't have a bug in your class that you claims are immutable.
A snippet from the Javadoc:
Of necessity this means that all
public fields are final, and that all
public final reference fields refer to
other immutable objects

Spring: How to assure that a class is only instantiated by spring and not by keyword new

Is it possible to assure that only spring can instantiate a class, and not by the keyword new at compile time? (To avoid instantiating by accident)
Thank you!
If you want to detect it at compile time, the constructor must be non-public.
Private is probably too strict (it makes code analysis tools assume it will never be called, and may even cause warnings in some IDEs), I'd say the default (no modifier, package protected) is best there. In cases you want to allow subclasses in other packages (but that's impossible without allowing calling the constructor directly from that subclass) you can make it protected.
Make sure to comment the constructor appropriately, so it is clear to anyone reading the code why the constructor is like that.
Spring will call this non-public constructor without any problems (since Spring 1.1, SPR-174).
The question if this not allowing anything else to call your constructor, the idea of forcing every user of a class to use the Spring dependency injection (so the whole goal of this question) is a good idea or not, is a whole different matter though.
If this is in a library/framework (that is just usually used with Spring), limiting the way it may be used might not be such a good idea. But if it's for classes that you know will only be used in your closed project, which already forces the use of Spring, it might make sense indeed.
Alternatively, if your real goal is just to avoid the possibility of someone creating an instance and not initializing it with its dependencies, you can just use constructor dependency injection.
And if your goal is only to prevent accidental usage of the constructor (by developers not aware that the class was supposed to be initialized by Spring), but don't want to totally limit possibilities, you can make it private but also add static factory method (with an explicit name like createManuallyInitializedInstance or something like that).
Bad idea: Another possible alternative is to make the constructor publicly available, but deprecate it. This way it can still be used (without resorting to hacks like using reflection) but any accidental usage will give a warning. But this isn't really clean: it is not what deprecation is meant for.
The only obvious way I can think of doing this is at Runtime via a massive hack; Spring works with normal Java after all (i.e. anything that can be accomplished in Spring must be accomplishable via standard Java - it's therefore impossible to achieve as a compile time check). So here's the hack:
//CONSTRUCTOR
public MyClass() {
try {
throw new RuntimeException("Must be instantiated from with Spring container!");
}
catch (RuntimeException e) {
StackTraceElement[] els = e.getStackTrace();
//NOW WALK UP STACK AND re-throw if you don't find a springframework package
boolean foundSpring = false;
for (StackTraceElements el : els) {
if (el.getDeclaringClass().startsWith("org.springframework")) {
foundSpring = true; break;
}
}
if (!foundSpring) throw e;
}
}
I really would not advise doing this!
While I can understand why you would want to ensure that a class is instantiated only by Spring, this is actually not a good idea. One of the purposes of dependency injection is to be able to easily mock out a class during testing. It should be possible, then, during unit tests to manually instantiate the various dependencies and mock dependencies. Dependency injection is there to make life easier, and so it is usually good to instantiate with DI, but there are cases where using new is perfectly sensible and one should be careful not to take any design pattern or idiom to the extreme. If you are concerned that your developers are going to use new where they should use DI, the best solution for that is to establish code reviews.
I'll tell you why not to do this - you won't be able to mock your classes. And thus you won't be able to make unit-tests.
Not sure if Spring supports this as I haven't tried, and haven't used Spring in quite awhile, however with another IOC container a sneaky route I once took was to make the class one wishes to be returned as your injected interface an abstract class, and have the IOC container return that as a derived class instance. This way no-one can create an instance of the class (as it's abstract) and the container can return a derived class of this.
The container itself will generate the definition of the derived class so there's no worry of someone trying to construct one of these
Write an aspect around the call to the constructor and abort if not via Spring
don't know about spring, but if you want to have some control on creating new instances, you should make constructor private, and create public static YourClass getInstance() method inside your class which will handle checks and return new instance of that object. You can then create new class with constructor whichi will call getInstance().. and hand that class to Spring. Soon you will discover places where you had that 'illegal' calls outside spring...

Designing Constructors for Testability

I'm working with some existing code, trying to add to it and increase the unit tests for it. But running into some problems with getting the code testable.
Original Constructor:
public Info() throws Exception
{
_ServiceProperties = new ServiceProperties();
_SshProperties = new SshProperties();
}
I'm aware that this is bad, and obviously not testable. In a junit environment, this class will fail to create every time since it wont be able to find the necessary properties to construct itself. Now, I'm aware this class would be a lot more testable with the simple change of moving anything prefaced with 'new' as a parameter.
So I end up with:
New Constructor:
public Info(ServiceProperties srvProps, SshProperties sshProps) throws Exception
{
_ServiceProperties = srvProps;
_SshProperties = sshProps;
}
Which allows me to properly unit test this Info class. The problem though, is now all that work is pushed to some other class:
Some Other Class' Method:
public void useInfo() throws Exception
{
ServiceProperties srvProps = new ServiceProperties();
SshProperties sshProps = new SshProperties();
Info info = new Info(srvProprs, sshProprs);
doStuffWithInfo(info);
}
Now this method isn't testable. All I've managed to do is push off where the constructions of these Property objects are occurring, and somewhere else some piece of code is going to be stuck actually having to call "new".
Here's the rub for me: I can't figure out how to break this chain of events of simply pushing these "new" calls somewhere else. What am I missing?
Look at using a Dependency Injection framework such as Spring. This application of Inversion of Control means that each of your types can avoid the pitfall you've seen, leaving the configuration to "wire" components together.
This introduction to Spring (pdf) gives a comprehensive overview of Spring. The first chapter or two should be sufficient to explain the concepts.
Also see Inversion of Control Containers and the Dependency Injection pattern by Martin Fowler
You have the right idea. Perhaps this will help you. I recommend you follow two rules for all your classes of significance, where "of significance" means if you don't follow the steps it will be more difficult to test, reuse, or maintain the class. Here are the rules:
never instantiate or self-acquire a dependency
always program to interfaces
You have a start at rule #1. You changed your Info class to no longer create its dependencies. By "dependency" I mean other classes, configuration data loaded from property files or whatever, etc. When you depend on how something is instantiated you are tying your class to it and making it more difficult to test, reuse and maintain. So, even if a dependency is created via a factory or a singleton, don't have your class create it. Have something else call create() or getInstance() or whatever and pass it in.
So you chose the "something else" to be the class that uses your class, and realized there is a bad smell to it. The remedy is to instead have the entry-point to your application instantiate all dependencies. In a traditional java app, this is your main() method. if you think about it, instantiating classes and hooking them up to each other, or "wiring" them together, is a special kind of logic: "application assembly" logic. Is it better to spread this logic throughout your code, or to collect it in one place to more easily maintain it? The answer is that collecting it in one place is better - not only for maintainance, but the act of doing so turns all your classes of significance into more useful and flexible components.
In your main() or equivalent of main() you should create all the objects you need, passing them into each others' setters and constructors to "wire" them together. Your unit tests would then wire them differently, passing in mock objects or similar things. The act of doing all this is called "dependency injection". After doing as I say, you will likely have a big ugly main() method. This is where a dependency injection tool can help you out and in fact make your code infinitely more flexible. The tool I would suggest when you get to this point, as others have also suggested, is Spring.
The less important rule #2 - always program to interfaces, is still very important because it eliminates all dependencies on implementation, making reuse much easier, not to mention leveraging other tools like mock object frameworks, ORM frameworks, etc. easier as well.
Even dependency injection frameworks like Spring, Guice, PicoContainer etc. need some sort of boostrap so you always have to build something up.
I would suggest you to use a provider/factory that returns a configured instance of you class. This would allow you to exit the "creation"-hierarchy.
Your constructors aren't incorrect and the problem isn't about when/where code is executed, it's about what everyone else mentioned: Dependency Injection. You need to create mock SshProperties objects to instantiate your object. The simplest way (assuming the class isn't marked as final) is to extend the class:
public class MockSshProperties extends SshProperties {
// implemented methods
}
You can you use mock frameworks like Mockito:
public class Info {
private final sshProps;
private final serviceProps;
public Info() {
this(new SshProperties(), new ServiceProperties());
}
public Info(SshProperties arg1, ServiceProperties arg2) {
this.sshProps = arg1;
this.serviceProps = arg2
}
}
public class InfoTester
{
private final static SshProperties sshProps = mock(SshProperties.class);
private final static ServiceProperties serviceProps = mock(ServiceProperties.class);
static {
when(sshProps.someGetMethod("something")).thenReturn("value");
}
public static void main(String[] args) {
Info info = new Info(sshProps, serviceProps);
//do stuff
}
}
The easiest answer is Spring. However another answer is to put your config stuff into JNDI.
Spring in some ways is a better answer, especially if you don't have anything that changes depending on environment.
You let the some-other-class have too much knowledge about the Info class and its dependencies. A dependency injection framework would use a provider class. Using generic types one can make a Provider of Info objects:
interface Provider<T> {
T get();
}
If your some-other-class take a Provider<Info> in its constructor your method would look like:
public void useInfo() throws Exception
{
Info info = infoProvider.get();
doStuffWithInfo(info);
}
This has removed construction of concrete classes from your code. Next step is to make Info into an interface to make it easier to create a mock for the specific unit-test case.
And yes, this will push and push all the object construction code further and further up. It will lead to some module that only describes how to wire things together. The "rules" for such code is that it should be free of conditional statements and loops.
I recommend reading Misko Heverys blog. All the presentations are useful and printing out the guide to writing testable code as little rulebook once you understand the rules is a good thing.

Categories