Reputation: 21981
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.
Upvotes: 4
Views: 9768
Reputation: 4332
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)
Upvotes: 0
Reputation: 6286
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>
Upvotes: 0
Reputation: 299208
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:
Upvotes: 6
Reputation: 2423
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 " />
Upvotes: 0