Tuesday, March 1, 2011

Spring Autowiring a property of an Enum

I wanted to be able to take a string from the database, the value of which was set from a .toString() call on an Enum, use it to get the proper enum with .valueOf(), and then call a method on the Enum to get an object that was Autowired by Spring.

The answer was to define each value of the Enum as a bean, following this example. The resulting beans don't need to be explicitly injected anywhere - when you call .valueOf(), you will get the proper Enum that has had its dependencies injected by Spring.

This allows the following:
Object o = (Enum.valueOf(databaseString)).toObject();

No comments: