1. 程式人生 > >Caused by: java.lang.IllegalArgumentException: At least one JPA metamodel must be present!

Caused by: java.lang.IllegalArgumentException: At least one JPA metamodel must be present!

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: At least one JPA metamodel must be present!


使用springboot做jdbcTemplate的注入時候,啟動報錯!!

原因:springboot已經配置了datasource的自動化配置,因為做了jpa的自動化配置去除導致

@Configuration
@EnableAutoConfiguration(exclude = {
        MetricExportAutoConfiguration.class,
        SecurityAutoConfiguration.class,
        ManagementWebSecurityAutoConfiguration.class,
       DataSourceAutoConfiguration.class,
       HibernateJpaAutoConfiguration.class,
       DataSourceTransactionManagerAutoConfiguration.class,
        MetricExportAutoConfiguration.class
})
@ComponentScan
@EnableDiscoveryClient
@EnableAspectJAutoProxy(proxyTargetClass = true)
@EnableFeignClients
@EnableScheduling
public class PackResolveServiceApp extends SpringBootServletInitializer {

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        SpringApplication.run(PackResolveServiceApp.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(PackResolveServiceApp.class);
    }
}
解決方式1:註釋掉  EnableAutoConfiguration 中datasource和hibernate相關的autoConfig,開啟自動化配置

在程式碼中就能使用jdbcTemplate:

    @Autowired
    DataSource dataSource;

    @Bean
    public JdbcTemplate jdbcTemplate() {
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        try {
            jdbcTemplate.setDataSource(this.dataSource);
            jdbcTemplate.setLazyInit(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jdbcTemplate;
    }

解決方式2:排除自動化配置,新增自定義配置檔案,如下