如何在Spring中获取泛型类型的类 [英] How to get class of generic type in Spring

查看:794
本文介绍了如何在Spring中获取泛型类型的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的spring项目中有一个泛型类DAO,我必须获取泛型T的类.我知道纯Java解决方案:

I have a generics class DAO in my spring project,I have to get class of generic T.I know the pure java solution:

class Foo<T> {
    final Class<T> typeParameterClass;

    public Foo(Class<T> typeParameterClass) {
        this.typeParameterClass = typeParameterClass;
    }

    public void bar() {
        // you can access the typeParameterClass here and do whatever you like
    }
}

但是,在春季项目中,我必须从"ApplicationContext"中获取Foo,我无法通过以下方式获取Foo:

But,in spring project,I have to get the Foo from the "ApplicationContext",I can't get Foo by:

Foo<ClassName> foo = new Foo<ClassName>(ClassName.class);

如何在Spring中获取通用类型的类.

How to get class of generic type in Spring.

推荐答案

Spring可以使用带参数的构造函数

Spring is able to use constructors with parameters

在Java配置中,这非常简单:

In java configuration, it is very simple :

@Configuration
public class MyConf {
    ...
    @Bean
    private foo() {
        return new Foo<ClassName>(ClassName.class);
    }
    ...
}

使用XML配置也可以

<bean id="foo" class="...Foo">
    <constructor-arg type="java.lang.Class" value="...ClassName"/>
</bean>

这篇关于如何在Spring中获取泛型类型的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆