创建名为'entityManagerFactory','dataSource'和'delegatingApplicationListener'的bean时出错

时间:2017-05-30 10:56:25

标签: java spring maven spring-boot

我需要一些帮助。 我有一个Spring项目,我正在迁移到Spring Boot项目。但是我有一些问题。 你能救我吗?

这是问题

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]

这是我的应用程序类

@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);
}

这是我的AppConfig类

@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;
    }
}

对旧的Spring项目使用相同的类,并适应作为Spring启动项目启动。任何人都有这个问题吗?

对于我的pom.xml我添加了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和Spring版本4.3.8

1 个答案:

答案 0 :(得分:0)

我有一个类似的问题,我通过将@ComponentScan({ "com.beni_regev" })添加到定义了我的DataSource的类并将dataSource bean更改为以下内容来解决它(我使用 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;
}