tags:

views:

71

answers:

4

Hey,

does anybody have a simple way of printing out bean property values ? Without complicated instrospection constructs via getting propertyDescriptors etc. I'm talking about testing and checking that all properties have correct values, during development.

A: 

Do you want to print out configuration properties which are built by propertyplaceholderconfiguerer or bean properties itself (which may be set manually via xml, has default values...)?

Michael
this should be posted as a comment indeed
Roman
properties itself
lisak
A: 

BeanPostProcessor may be able to help you. postProcessBeforeInitialization() method will be called for each bean initialization and you can print values of properties there.

Post processor class:

public class ExampleBeanPostProcessor implements BeanPostProcessor {
    public Object postProcessBeforeInitialization(Object bean, String beanName)
        throws BeansException {
        if (bean instanceof YourBean)
            System.out.println((YourBean) bean).getSomeProp());
        return bean;
    }
    public Object postProcessAfterInitialization(Object bean, String beanName)
        throws BeansException {
        return bean;
    }
}

Declare bean in bean file:

<bean class="ExampleBeanPostProcessor " />
Jaydeep
You probably didn't read the last sentence of my question.
lisak
+2  A: 

PropertyDescriptors are the way to go, but Spring makes using them a lot easier if you use the BeanWrapper interface.

Here's a stupid test class:

public class Thingy{
    private final String foo = "hey";
    private final int bar = 123;
    private final List<String> grr = Arrays.asList("1", "2", "3");

    public String getFoo(){
        return this.foo;
    }
    public int getBar(){
        return this.bar;
    }
    public List<String> getGrr(){
        return this.grr;
    }
}

And here's a main method to inspect an instance of it:

public static void main(final String[] args) throws Exception{
    final Thingy thingy = new Thingy();
    final BeanWrapper wrapper = new BeanWrapperImpl(thingy);
    for(final PropertyDescriptor descriptor : wrapper.getPropertyDescriptors()){
        System.out.println(descriptor.getName() + ":"
            + descriptor.getReadMethod().invoke(thingy));
    }
}

Output:

bar:123
class:class com.mypackage.Thingy
foo:hey
grr:[1, 2, 3]

Read this for reference:

seanizer
Thank you seanizer, that's what I was looking for.
lisak
@seanizer, I did it exactly as you said. This is the bean http://pastebin.com/242qAqHD . Only "progression" property wasn't set, otherwise the rest of bean properties was fully initialized with data. and the result is that "progression: ", "movement:null", "startingPos:null" .... so that for movement and startingPos something went wrong...
lisak
@lisak that's strange. check this out: http://pastebin.com/Y7NmRdNi when I execute this, the properties are there
seanizer
@seanizer, you're right, the problem is somewhere else, thank you
lisak