Inject Enum of java 5 in Spring Framework:-
Spring framework is popular opensource framework developing applicaitons in java.
Enum is java enumeration keyword introduced in java 5 features.
ususally, In Spring configuraiton file, we will inject different custom classes as well as predefined classes like Integer,String.
But injecting enum class in spring container is different as if we not correctly inject, we will end of with exceptions like "org.springframework.beans.TypeMismatchException: Failed to convert property value of type".
so what is the solution of avoiding TypeMismatchException in spring? The solution is to use either custom property editors in spring custom configuraiton files
we have to conver the enum to string to inject enum to class in spring.
This tutorials is to find out the ways to inject enum objects in spring.
here is the enum defination java class
package com.cloudhadoop.constants;
enum Day {
MONDAY(0), TUESDAY(1), WEDNESDAY(2), THURSDAY(3), FRIDAY(4), SATURDAY(5), SUNDAY(
6);
private final int dayNumber;
private Day(int dayNumber) {
this.dayNumber = dayNumber;
}
public int getDayNumber() {
return dayNumber;
}
}
There are many ways to inject the enum object of java 5 in spring framework
one way is to inject the enum single value using enumProperty as described in the below screenshot
spring property editors are internally assigned the correct value to enum property
second approach is to inject using factory-method as in below screen shot.
The above approaches is light weight and spring container validates the configuraiton when container is stated
or other approach is to as is to assign all enum values using util:constant tag
This approach provides for bean validation in IDE's at development time. Please click below screenshot for the spring code configuration file.
The three apporaches works with enum in java with spring 2.5.6 version
Please share your comments on this topics

0 comments:
Post a Comment