以下に示すように、クラスを拡張するときに定義されるジェネリック型を持つ 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 );
}
}