开发者

java/spring printing out bean property values

does anybody have a simple way of printing o开发者_开发知识库ut 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.


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:

  • Bean manipulation and the BeanWrapper


JSR-305: Annotations for Software Defect Detection


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 " />


For a one liner can use the gson library.

new Gson().toJson(myObject)

For maven:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.1</version>
    <scope>test</scope> <!-- remove you use gson in production -->
</dependency>


Add custom <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

where

 @Override
    protected String resolvePlaceholder(String placeholder, Properties props) 

@Override
    protected String resolvePlaceholder(String placeholder, Properties props, int             systemPropertiesMode) 

    @Override
    protected String resolveSystemProperty(String key) 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜