Tuesday, March 22, 2016

Spring Annotations: Using Constructor Arugments with @Autowired


Introduction

I've struggled for weeks with wanting to use a constructor with arguments along with Spring Annotations (in particular @Autowired) but most blog posts and tutorials say that this isn't possible or needs to use Spring Expressions.

Hypothesis

There has got to be some way to do this.  The alternative I have been using was to have an empty object autowired in and then manually run a bunch of setters to inject the required configuration.  This ends up being error prone and verbose to verify (e.g. every public method has to check that the required fields are not null).

Results

After searching the web for a long time I finally found that you CAN use multi-argument constructors if you refrain from using the @Component or @Service annotations and instead create the classes in a @Configuration class with @Bean annotations.  After creating a class (manually, with new) you can autowire it by using AutowireCapableBeanFactory.autowireBean(Object) method.

Conclusion

My code is a lot more readable and simple now, and let me find a few subtle bugs that did not turn up in the unit tests.  I ended up with complex object creation logic, but it is out in the @Configuration classes instead of inside of the core objects.  I am much happier with this situation.

Tuesday, March 8, 2016

Java Lambdas and Interrupted Exceptions

I couldn't figure out why my application was taking 40+ seconds to shut down.  It turned out that a long-running process was in a Lambda expression and was completely ignoring the owning thread being shut-down.  Changing the code to a foreach loop fixed the problem.

It looks like foreach loops are still useful in Java 8 after all.

Short post today - not feeling well.

Wednesday, March 2, 2016

Great for Karaoke: Hack Star

I was sick and overworked on Tuesday (who isn't!), so this slightly-late post it may be a bit off topic.

It's a parody, in the spirit of Weird Al or James@War, of Nickleback's Rockstar: Hack Star.

It isn't 100% polished, but it's been in my head since 2006!  If you look at the lyrics, it's roughly the 6 - 8th paragraphs.

We all want to be big hack stars,
With the Internet using all our Zips and WARs.
We'll have so many gadgets it'll be real neat,
No one will understand us cuz we'll all speak Leet.
And, we'll have the cash to live like Tzars,
hard work and talent will take you real darn far.
We'll have our competition ripping out their hair,
they'll complain to congress that it's just not fair,
and well,

Hay hay I want to be a hack star
Hay hay I want to be a hack star

We'll make apps so leet they'll augment your senses,
Me and my homies have our certs from Mensa.
I'll hack so hard that it takes up half my brain,
I'll hack so hard that drives me half insane.

Hay hay I want to be a hack star
Hay hay I want to be a hack star