Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Class value to spring bean property?

Hey, what is the best way to set a bean's property with Class value ? Regarding XML configuration. For a bean like this :

public class FilterJsonView extends MappingJacksonJsonView {

    private Set<String> filteredAttributes;
    private Class clazz;

    public Set<String> getFilteredAttributes() {
        return filteredAttributes;
    }

    public void setFilteredAttributes(Set<String> filteredAttributes) {
        this.filteredAttributes = filteredAttributes;
    }

    public Class getClazz() {
        return clazz;
    }

    public void setClazz(Class clazz) {
        this.clazz = clazz;
    }
}
like image 787
lisak Avatar asked Apr 29 '11 15:04

lisak


People also ask

How do you inject the value of a bean property in spring?

Most people know that you can use @Autowired to tell Spring to inject one object into another when it loads your application context. A lesser known nugget of information is that you can also use the @Value annotation to inject values from a property file into a bean's attributes.

Can we use @bean on class?

Yes, we can.

What are different ways to configure a class as spring bean?

Different Methods to Create a Spring Bean Creating Bean Inside an XML Configuration File (beans. xml) Using @Component Annotation. Using @Bean Annotation.


2 Answers

Just inject the class name, and Spring will convert it to a Class object for you, e.g.

<bean class="com.x.y.FilterJsonView">
   <property name="clazz" value="com.x.y.SomeClass"/>
</bean>
like image 141
skaffman Avatar answered Sep 24 '22 10:09

skaffman


Just supply the class name. Say you want clazz to be String.class:

<bean id="beanId" class="FilterJsonView">
    <property name="clazz" value="java.lang.String"/>
</bean>

Spring has a PropertyEditorSupport implementation called ClassEditor that handles the conversions.

like image 43
laz Avatar answered Sep 25 '22 10:09

laz