简体   繁体   中英

Error creating bean with name 'entityManagerFactory' , 'dataSource' and 'delegatingApplicationListener'

I need some help. I have a Spring project and I'm migrating to a Spring Boot project. but I'm having some issue. could you help me?

this is the problem

2017-05-30 07:39:32.067  INFO 60280 --- [           main]     f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject'     annotation found and supported for autowiring
2017-05-30 07:39:32.332  INFO 60280 --- [           main]     trationDelegate$BeanPostProcessorChecker : Bean 'appConfig' of type     [com.santander.portalcio.config.AppConfig$$EnhancerBySpringCGLIB$$c8cc79c0] is     not eligible for getting processed by all BeanPostProcessors (for example: not     eligible for auto-proxying)
2017-05-30 07:39:32.343  INFO 60280 --- [           main]     trationDelegate$BeanPostProcessorChecker : Bean     'org.springframework.transaction.annotation.ProxyTransactionManagementConfigurat    ion' of type     [org.springframework.transaction.annotation.ProxyTransactionManagementConfigurat    ion$$EnhancerBySpringCGLIB$$4fca10c8] is not eligible for getting processed     by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-05-30 07:39:32.412  WARN 60280 --- [           main]     s.c.a.AnnotationConfigApplicationContext : Exception encountered during context     initialization - cancelling refresh attempt:     org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating     bean with name 'entityManagerFactory' defined in class path resource     [com/santander/portalcio/config/AppConfig.class]: Unsatisfied dependency     expressed through method 'entityManagerFactory' parameter 0; nested exception is     org.springframework.beans.factory.BeanCreationException: Error creating bean     with name 'dataSource' defined in class path resource     [com/santander/portalcio/config/AppConfig.class]: Bean instantiation via factory     method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.jdbc.datasource.lookup.DataSourceLookupFailureException: Failed to look up JNDI DataSource with name 'jdbc/PortalCIO'; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
2017-05-30 07:39:32.420  WARN 60280 --- [           main] o.s.boot.SpringApplication               : Error handling failed (Error creating bean with name 'delegatingApplicationListener' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration': Initialization of bean failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry' available)
2017-05-30 07:39:32.431 ERROR 60280 --- [           main] o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory' defined in class path resource [com/santander/portalcio/config/AppConfig.class]: Unsatisfied dependency expressed through method 'entityManagerFactory' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [com/santander/portalcio/config/AppConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.jdbc.datasource.lookup.DataSourceLookupFailureException: Failed to look up JNDI DataSource with name 'jdbc/PortalCIO'; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:467) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]

This is my Application class

@SpringBootApplication
public class Application extends SpringBootServletInitializer {

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
    return configureApplication(builder);
}

public static void main(String[] args) {
    configureApplication(new SpringApplicationBuilder()).run(args);
}

private static SpringApplicationBuilder configureApplication(SpringApplicationBuilder builder) {
    return builder.sources(Application.class);
}

This is my AppConfig class

@Configuration
@EnableTransactionManagement
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class AppConfig {

 @Bean
 public ServletRegistrationBean wsservletRegistration(WSServlet
 wsservletServlet) {
 ServletRegistrationBean registration = new ServletRegistrationBean(
 wsservletServlet);
 registration.addUrlMappings("/indicadoresBSTS*");
 return registration;
 }

@Bean
public FilterRegistrationBean filterRegistrationBean() {

    FileUploadFilter fileUploadFilter = new FileUploadFilter();

    CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();

    FilterRegistrationBean registrationBean = new FilterRegistrationBean();

    registrationBean.setFilter(fileUploadFilter);
    registrationBean.setFilter(characterEncodingFilter);

    return registrationBean;
}

@Bean
public DataSource dataSource() {
    JndiDataSourceLookup dsLookup = new JndiDataSourceLookup();
    dsLookup.setResourceRef(true);
    DataSource ds = dsLookup.getDataSource("jdbc/PortalCIO");
    return ds;
}

@Bean
public AbstractPlatformTransactionManager txManager(EntityManagerFactory emf) {
    return new JpaTransactionManager(emf);
}

@Bean
public PropertiesFactoryBean hibernateProperties() {
    PropertiesFactoryBean bean = new PropertiesFactoryBean();
    bean.setLocations(new ClassPathResource("hibernate.properties"),
            new ClassPathResource("hibernate-test.properties"));
    bean.setIgnoreResourceNotFound(true);
    return bean;
}

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource,
        Properties hibernateProperties) {
    LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean();
    bean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
    bean.setDataSource(dataSource);
    bean.setPersistenceXmlLocation("classpath*:META-INF/spring-persistence.xml");
    bean.setJpaProperties(hibernateProperties);
    return bean;
}

@Bean
public BeanPostProcessor customFunctionRegister() {
    return new CustomFunctionRegisterPostProcessor();
}

public static class CustomFunctionRegisterPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    @SuppressWarnings("unchecked")
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (!(bean instanceof EntityManagerFactory)) {
            return bean;
        }

        HibernateJpaSessionFactoryBean fac = new HibernateJpaSessionFactoryBean();
        fac.setEntityManagerFactory((EntityManagerFactory) bean);
        SessionFactoryImplementor sfi = (SessionFactoryImplementor) fac.getObject();

        SQLFunctionRegistry reg = sfi.getSqlFunctionRegistry();
        Field userFunctionsField;
        Map<String, SQLFunction> userFunctions;
        try {
            userFunctionsField = SQLFunctionRegistry.class.getDeclaredField("userFunctions");
            userFunctionsField.setAccessible(true);

            userFunctions = (Map<String, SQLFunction>) userFunctionsField.get(reg);
        } catch (Exception e) {
            throw new BeanInitializationException("can't read SQLFunctionRegistry.userFunctions", e);
        }

        Dialect dialect = sfi.getDialect();
        userFunctions.put("datediff_minutes", new DateDiffFunction(dialect, TimePart.minute));
        userFunctions.put("datetrunc_day", new DateTruncFunction(dialect, DatePart.day));
        userFunctions.put("datetrunc_month", new DateTruncFunction(dialect, DatePart.month));

        return bean;
    }
}

A use the same classes for the old spring project and adapt to start as a Spring boot Project. could anyone have this problems?

for my pom.xml I add spring-boot-starter-parent 1.5.3, spring-boot-starter-web, spring-boot-starter-security, spring-boot-starter-data-mongodb, spring-boot-starter-remote-shell and Spring version 4.3.8

I had a similar problem and I solved it by adding @ComponentScan({ "com.beni_regev" }) to the class where my DataSource is defined and changing the dataSource bean to the following (I'm using Postgres ):

@Bean
public DataSource dataSource() {
   DriverManagerDataSource dataSource = new DriverManagerDataSource();
   dataSource.setDriverClassName("thread");
   dataSource.setUrl("jdbc:postgresql://localhost:5432/my_db?loglevel=0");
   dataSource.setUsername(""postgres);
   dataSource.setPassword("admin");
   dataSource.setSchema("public");
   return dataSource;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM