How to set Class value to spring bean property?

2019-02-16 06:38发布

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

2条回答
等我变得足够好
2楼-- · 2019-02-16 06:49

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>
查看更多
我只想做你的唯一
3楼-- · 2019-02-16 06:57

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.

查看更多
登录 后发表回答