【发布时间】:2018-01-25 23:45:44
【问题描述】:
我有一个 Spring Boot 应用程序,它通过 Maven 的 mvn spring-boot:run 命令运行良好。但是,当我尝试通过 IDE(在我的情况下为 Intellij IDEA 2017.2.1)运行它时,它会失败,因为它无法 @Autowire 数据源。
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in com.myApp.Application required a bean of type 'javax.sql.DataSource' that could not be found.
Action:
Consider defining a bean of type 'javax.sql.DataSource' in your configuration.
这个代码库的原始作者有一个主类,它启动应用程序,接受数据源的构造函数参数,这是我不熟悉的一种方法,因为我习惯于通过application.properties 文件来完成它并让Spring Boot 连接它自己的 DataSource。
@EnableTransactionManagement
@SpringBootApplication
@EnableCaching
public class Application extends JpaBaseConfiguration {
protected Application(DataSource dataSource, JpaProperties properties,
ObjectProvider<JtaTransactionManager> jtaTransactionManagerProvider,
ObjectProvider<TransactionManagerCustomizers> transactionManagerCustomizers) {
super(dataSource, properties, jtaTransactionManagerProvider, transactionManagerCustomizers);
}
在 IDEA 中,我注意到此构造函数的 datasource 和 properties 参数带有红色下划线。对于datasource,IDE 抱怨存在两个bean,它不知道在XADataSourceAutoConfiguration.class 和DataSourceConfiguration.class 之间自动装配哪个。至于用红色下划线的构造的另一个参数properties,它找不到任何bean,IDE 抱怨没有找到JpaProperties 类型的bean。以下是在主应用程序启动类中覆盖的其他一些方法,
@Override
protected AbstractJpaVendorAdapter createJpaVendorAdapter() {
return new HibernateJpaVendorAdapter();
}
@Override
protected Map<String, Object> getVendorProperties() {
Map<String, Object> vendorProperties = new LinkedHashMap<>();
vendorProperties.putAll(getProperties().getHibernateProperties(getDataSource()));
return vendorProperties;
}
public static void main(final String[] args) {
SpringApplication.run(Application.class, args);
}
不幸的是,因为我不熟悉这种在 Spring Boot 中使用构造函数来配置/自动配置应用程序的方法,所以我不确定一些事情,但我的确切问题是为什么应用程序在 Maven 中运行良好但不在 Intellij IDEA 中?此外,由于我无法访问该专有代码库的原始作者,我很想知道为什么,如果有人甚至可以给我提示,他们已经配置了构造函数,而不是默认的自动配置。我也有一个集成测试,我写了我正在尝试运行,但是这个测试,无论是通过 IDE 还是通过 Maven 的故障安全插件运行,也会导致同样的错误,DataSource 不是@Autowired。所以这是另一个问题,为什么这个测试不会在主应用程序运行时通过 Maven 运行。这是我的集成测试,
@RunWith(SpringJUnit4ClassRunner.class)
@WebMvcTest(value = TransactionController.class, secure = false)
public class TransactionControllerIT {
@Autowired
MockMvc mockMvc;
@Test
public void shouldInitiateTransfer() {
String transferTransaction =
"some json string I can't show here on stack overflow";
RequestBuilder requestBuilder = MockMvcRequestBuilders
.post("/begin-transfer")
.accept(MediaType.APPLICATION_JSON).content(transferTransaction)
.contentType(MediaType.APPLICATION_JSON);
MvcResult result = null;
try {
result = mockMvc.perform(requestBuilder).andReturn();
} catch (Exception e) {
fail("Exception in integration test!");
}
MockHttpServletResponse response = result.getResponse();
assertEquals(HttpStatus.CREATED.value(), response.getStatus());
}
}
感谢您阅读我的问题。
【问题讨论】:
标签: spring maven spring-boot intellij-idea