Java/Spring打印出Bean属性值

4

有没有一种简单的方法打印出bean属性值?不需要通过获取propertyDescriptors等复杂的内省结构。我说的是在开发过程中测试和检查所有属性是否具有正确的值。

5个回答

6

PropertyDescriptors是解决问题的方法,但如果使用BeanWrapper接口,Spring会让使用它们变得更加容易。

这是一个愚蠢的测试类:

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;
    }
}

这里有一个主方法来检查它的实例:

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));
    }
}

输出:

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

阅读以下内容以供参考:


我按照你说的做了。这是豆子 http://pastebin.com/242qAqHD 。只有"progression"属性没有设置,否则bean的其余属性都已经完全初始化了数据。结果是"progression: ","movement:null","startingPos:null"....所以对于movement和startingPos来说,出了些问题... - lisak
@lisak 这很奇怪。看看这个:http://pastebin.com/Y7NmRdNi 当我执行这个时,属性就在那里。 - Sean Patrick Floyd

0

BeanPostProcessor 可能会对您有所帮助。postProcessBeforeInitialization() 方法将在每个 bean 初始化时被调用,您可以在其中打印属性的值。

后处理器类:

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;
    }
}

在 bean 文件中声明 bean:

<bean class="ExampleBeanPostProcessor " />

0

对于一行代码可以使用 gson 库。

new Gson().toJson(myObject)

对于 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>

0

添加自定义<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

其中

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

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

    @Override
    protected String resolveSystemProperty(String key) 


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接