开发者

Creation of generic type using Spring Config

开发者 https://www.devze.com 2022-12-12 16:48 出处:网络
How can I instantiate a bean with generic type using Spring config public cla开发者_C百科ss GenericService<T>

How can I instantiate a bean with generic type using Spring config

public cla开发者_C百科ss GenericService<T> 
{
 ...
}

Note that T is not the concrete type of a bean property. It is really just the type for one of the methods of the service.

In other words.. Can I instantiate new GenericService of type String or new GenericService of type Long using Spring context.

My generic class contains

public <T extends WordplayService> List<S> performTheService(String word, Class<T> clazz) 
{ 
    return clazz.newInstance().getAllWords(); 
    ...
}

The return type of the generic method depends on the concrete parameter type of the class instantiated. Is this possible or a wrong usage of DI + generics? TIA


Generics are a compile-time concept, while spring context is loaded at runtime, so they don't intersect. What exactly are you trying to achieve? What is your usecase.


You can safely use DI with generics, because as I said, generics are lost at the time when the dependencies are injected.

Generics are a compile-time concept ...

The truth is, Generic information is not (completely) erased at compile time. You can still retrieve this information via reflection, and that is what the Spring DI container does already for collections. See 3.3.3.4.2. Strongly-typed collection (Java 5+ only) in 2.0.8 Spring documentation (sorry can only post one hyperlink).

However, I do not know (yet) if it is possible to instruct the container to do that for your custom classes as well.

If you want to know how to retrieve this information at runtime, here's the original post from Neal Gafter: http://gafter.blogspot.com/2006/12/super-type-tokens.html


You should just instantiate it using the raw class name. As @Bozho says generics are a compile-time only construct and their full types are not available at runtime.


None of the answers shows any examples, its easy :

@Resource
private CommentService<String> stringCommentService;

@Resource
private CommentService<Integer> integerCommentService;

@Test
public void genericTest(){
    System.out.println("Generic test .... :");
    stringCommentService.printType("test");

    System.out.println("INT Generic test .... :");
    integerCommentService.printType(9);

}

Where commentservice looks like you'd imagine:

@Service
public class CommentService<T> {
0

精彩评论

暂无评论...
验证码 换一张
取 消