我想提供一个基本配置类,它将处理创建具有泛型类型的 bean,该泛型类型在您扩展类时定义,如下所示。但它从不调用@Bean
方法。
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.client.RestTemplate;
import java.lang.reflect.Constructor;
@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration( classes = { TestGenericBean.MyClientCreator.class } )
public class TestGenericBean
{
/* This throws an error saying no bean provided */
@Autowired
private TestClient client;
public static class ClientConfig<T>
{
private Class<T> classCreator;
public ClientConfig(Class<T> classCreator)
{
this.classCreator = classCreator;
}
/* This is never called */
@Bean
public T createClient(RestTemplate restTemplate) throws Exception
{
Constructor<T> constructor = classCreator.getConstructor(
RestTemplate.class
);
return constructor.newInstance( restTemplate );
}
/* This is never called */
@Bean
public RestTemplate restTemplate()
{
return new RestTemplate();
}
}
@Configuration
public static class MyClientCreator extends ClientConfig<TestClient>
{
public MyClientCreator()
{
super( TestClient.class );
}
}
public static class TestClient
{
public RestTemplate restTemplate;
public TestClient(RestTemplate restTemplate)
{
this.restTemplate = restTemplate;
}
}
@Test
public void testBean()
{
System.out.print( client.restTemplate );
}
}