我有一个创建 bean 的 Spring Boot 基础抽象配置类。如果我从它继承,bean 将在我的控制器之后创建(它需要自动连接它,因此失败)。注意:它确实是在控制器之后创建的。所以它不能自动连接,但必须通过appContext.getBean( BeanType.class )
如果我改为覆盖子类中的 bean 方法,那么它会在控制器之前创建,并且可以自动连接。
我该如何解决这个问题并使超类 bean 定义与子类同时加载?
@SpringBootApplication
public class ChildConfig extends ParentConfig<PCTestBean>
{
public ChildConfig()
{
super();
}
@Override
public PCTestBean getT()
{
return new PCTestBean();
}
}
public abstract class ParentConfig<T>
{
public ParentConfig() {}
@Bean
public T createTestBean()
{
return getT();
}
public abstract T getT();
}
public class PCTestBean
{
}
@RestController
@RequestMapping( "/client" )
public class MyController
{
@Autowired
private PCTestBean pcTestBean;
@RequestMapping( "/get" )
@ResponseBody
public String getClient(HttpServletRequest request) throws Exception
{
return pcTestBean.toString();
}
}
@RunWith( SpringJUnit4ClassRunner.class )
@SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT
)
@ContextConfiguration(
classes = {
ChildConfig.class
}
)
public class TestConfigs
{
@LocalServerPort
private String port;
private MockMvc mockMvc;
@Autowired
private WebApplicationContext context;
@Before
public void setUp() throws Exception
{
mockMvc = MockMvcBuilders
.webAppContextSetup( context )
.build();
}
@Test
public void testValidCall() throws Exception
{
MvcResult result = mockMvc.perform(
MockMvcRequestBuilders.get( new URI( "http://localhost:" + port + "/client/get" ) )
)
.andExpect( MockMvcResultMatchers.status().isOk() ).andReturn();
System.out.println( result.getResponse().getContentAsString() );
}
}