Wednesday, April 2, 2014

Spring IoC and PropertyEditors

Built-in PropertyEditor implementations

Spring IoC uses the concept of PropertyEditors to effect the conversion between an Object and a String. Below is a properties file containing values, which exist as strings and a Bean, which will be injected with the values.

/********* properties file begin  ***********/

threadPoolTaskExecutor.maxPoolSize=10
threadPoolTaskExecutor.running=true

/********* properties file end***********/

In a Bean, I have the following:
/********* bean begin  ***********/
    private Boolean running;

    public Boolean isRunning() {
        return running;
    }

    @Value("${threadPoolTaskExecutor.running}")
    public void setRunning(Boolean running) {
        this.running = running;
    }
/********* bean end ***********/

To convert the "running" attribute from a String to a Boolean Spring uses by default its CustomBooleanEditor class. To allow more elaborate conversion one can  register additional custom PropertyEditors describe in the spring reference manual. Below is summary of the possibilities taken from the manual.

When setting bean properties as a string value, a Spring IoC container ultimately uses standard JavaBeans PropertyEditors to convert these Strings to the complex type of the property. Spring preregisters a number of custom PropertyEditors (for example, to convert a classname expressed as a string into a real Class object). Additionally, Java's standard JavaBeans PropertyEditor lookup mechanism allows a PropertyEditor for a class simply to be named appropriately and placed in the same package as the class it provides support for, to be found automatically.

If there is a need to register other custom PropertyEditors, there are several mechanisms available. The most manual approach, which is not normally convenient or recommended, is to simply use the registerCustomEditor() method of the ConfigurableBeanFactory interface, assuming you have a BeanFactory reference. Another, slightly more convenient, mechanism is to use a special bean factory post-processor called CustomEditorConfigurer. Although bean factory post-processors can be used with BeanFactory implementations, the CustomEditorConfigurer has a nested property setup, so it is strongly recommended that it is used with the ApplicationContext, where


   
 

No comments:

Post a Comment