当前位置: 首页 > 知识库问答 >
问题:

Spring HiberNate:sessionFactory.get货币会话()导致NullPointerExc的结果

穆轶
2023-03-14

我使用的是Spring 4.3.2.RELEASE和Hibernate 4.3.11.RELEASE。一旦我自动连线任何刀,我就会得到一个NullPointerException。在Dao实现中,我自动连接sessionFactory,然后使用sessionFactory.getCurrentSession()。错误消息本身是一个长嵌套异常,最终导致以下情况:

Exception during lifecycle processing
java.lang.Exception: java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'applicationStartup': Unsatisfied dependency expressed through field 'batchjobDao': Error creating bean with name 'batchjobDaoImpl': Unsatisfied dependency expressed through field 'sessionFactory': Error creating bean with name 'sessionFactory' defined in com.TayrosCapital.investsuiteNG.config.Config: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.hibernate.SessionFactory]: Factory method 'sessionFactory' threw exception; nested exception is java.lang.NullPointerException; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in com.TayrosCapital.investsuiteNG.config.Config: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.hibernate.SessionFactory]: Factory method 'sessionFactory' threw exception; nested exception is java.lang.NullPointerException; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'batchjobDaoImpl': Unsatisfied dependency expressed through field 'sessionFactory': Error creating bean with name 'sessionFactory' defined in com.TayrosCapital.investsuiteNG.config.Config: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.hibernate.SessionFactory]: Factory method 'sessionFactory' threw exception; nested exception is java.lang.NullPointerException; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in com.TayrosCapital.investsuiteNG.config.Config: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.hibernate.SessionFactory]: Factory method 'sessionFactory' threw exception; nested exception is java.lang.NullPointerException
    at com.sun.enterprise.web.WebApplication.start(WebApplication.java:168)
    at org.glassfish.internal.data.EngineRef.start(EngineRef.java:122)
    at org.glassfish.internal.data.ModuleInfo.start(ModuleInfo.java:291)
    at org.glassfish.internal.data.ApplicationInfo.start(ApplicationInfo.java:352)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:500)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:219)
    at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:491)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:539)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:535)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:360)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:534)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:565)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:557)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:360)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:556)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1464)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1300(CommandRunnerImpl.java:109)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1846)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1722)
    at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:534)
    at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:224)
    at org.glassfish.grizzly.http.server.StaticHttpHandlerBase.service(StaticHttpHandlerBase.java:189)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
    at java.lang.Thread.run(Thread.java:745)

我的配置类与sessionFactory bean看起来像这样:

@Configuration
@ComponentScan("com.TayrosCapital.investsuiteNG")
@EnableWebMvc
@EnableTransactionManagement
@Import({SecurityConfig.class})
@PropertySource("classpath:properties/application.properties")
public class Config extends WebMvcConfigurerAdapter {

    @Autowired
    private Environment env;

    /**
     * Provides the functionality to support the @PropertySource annotation
     * 
     * @return 
     */
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfig() {
        PropertySourcesPlaceholderConfigurer propertyConfig = new PropertySourcesPlaceholderConfigurer();
        return propertyConfig;
    }

    /**
     * Provides the dataSource for the database access
     * 
     * @return 
     */
    @Bean(name = "dataSource")
    public DriverManagerDataSource dataSource() {        
        DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
        driverManagerDataSource.setDriverClassName(env.getProperty("database.driver"));
        driverManagerDataSource.setUrl(env.getProperty("database.url"));
        driverManagerDataSource.setUsername(env.getProperty("database.username"));
        driverManagerDataSource.setPassword(env.getProperty("database.password"));
        return driverManagerDataSource;
    }

    /**
     * viewResolver to set the prefix and suffix for the views
     * 
     * @return 
     */
    @Bean(name = "viewResolver")
    public InternalResourceViewResolver viewResolver() {        
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/xhtml/");
        viewResolver.setSuffix(".xhtml");
    return viewResolver;
    }

    /**
     * runs flyway to handle SQL migrations
     * 
     * @return 
     */
    @Bean(initMethod = "migrate")
    public Flyway flyway() {
        Flyway flyway = new Flyway();
        flyway.setLocations("classpath:sql");
        flyway.setDataSource(dataSource());
        return flyway;
    }

    /**
     * provides the entity manager
     * 
     * @return 
     */
    @Bean(name = "entityManagerFactory")
    @DependsOn("flyway")
    public EntityManagerFactory entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean();
        bean.setDataSource(dataSource());        
        return bean.getObject();
    }

    /**
     * Provides a session factory for hibernate db access
     * 
     * @param dataSource
     * @return 
     */
    @Autowired
    @Bean(name = "sessionFactory")
    @DependsOn("flyway")
    public SessionFactory sessionFactory(DataSource dataSource) {
        LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
        sessionBuilder.scanPackages("com.TayrosCapital.investsuiteNG");
        sessionBuilder.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
        sessionBuilder.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));

       return sessionBuilder.buildSessionFactory();
    }

    /**
     * Hibernate transaction manager to be able to use @Transactional annotation
     * 
     * @param sessionFactory
     * @return 
     */
    @Autowired
    @Bean(name = "transactionManager")
    public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager(sessionFactory);
        return transactionManager;                
    }

    /**
     * Defines where the resources for the website are located, e.g. css files
     * 
     * @param registry 
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/WEB-INF/resources/**");
    }    
}

[Edit]:这里有一个例子,我使用sessionFactory

@Repository
public class BatchjobDaoImpl extends ExtendedGenericDaoImpl<Batchjob, Integer> implements BatchjobDao {

    @Autowired
    private SessionFactory sessionFactory;

    /**
     * Will return a batchjob with the given className
     * 
     * @param className
     * @return A Batchjob
     */
    @Override
    @Transactional
    public Batchjob getByClass(String className) {
        String hql = "FROM Batchjob WHERE clazz=:className";
        Query query = sessionFactory.getCurrentSession().createQuery(hql);
        query.setParameter("className", className);
        query.setMaxResults(1);

        List<Batchjob> list = (List<Batchjob>)query.list();

        if(list != null && !list.isEmpty()) {
            return list.get(0);
        }

        return null;
    } 
}

[编辑]我的应用程序属性:

# settings for the database
database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/database?useUnicode=yes&characterEncoding=UTF-8
database.username=user
database.password=password

# settings for hibernate
hibernate.show_sql=false
hibernate.dialect=org.hibernate.dialect.MySQLDialect

共有1个答案

艾凌龙
2023-03-14

可能我在这里的猜测是@Autowired环境;在创建 Bean 之前尚未初始化。更好的选择是连接环境感知接口

@Configuration
@ComponentScan("com.TayrosCapital.investsuiteNG")
@EnableWebMvc
@EnableTransactionManagement
@Import({SecurityConfig.class})
@PropertySource("classpath:properties/application.properties")
public class Config extends WebMvcConfigurerAdapter implements EnvironmentAware{

private Environment environment;

    @Override
    public void setEnvironment(final Environment environment) {
        this.environment = environment;
    }


///other beans instantiations

}

或者你可以试试

@Resource
public Environment env;
 类似资料:
  • 我试过... 但那就不允许便士条目了。 我想要增量按钮控制在英镑上升,但仍然想要输入便士的能力。 谢谢,1DMF

  • 我正在尝试使用函数。 而它应该打印$符号或美元? 我使用linux主机。 谢谢

  • 这是一篇加密货币的入门文章,是写给没有接触过比特币、加密货币的小伙伴的入门指南,接下来的内容,都将与加密货币相关。 前言 “加密货币就是货币”听起来挺“白痴的”。想想背后的意思,言外之意就是“加密货币可能不是货币”,就非常值得玩味了。事实上,在我接触的很多朋友当中,一开始认为后者的更多。包括我自己,也是经过探究一段时间之后,才认定这个结论的。 惯性定律不仅存在于物质世界,也存在于人类的认知世界。人

  • 问题内容: 我正在使用我给定的语言环境获取自定义货币格式。但是,这始终包含我不需要的货币符号,我只想要给定语言环境的正确货币数字格式而没有货币符号。 做一个抛出一个异常.. 问题答案: 以下作品。这有点丑陋,但可以履行合同: 您还可以从货币格式中获取模式,删除货币符号,然后从新模式中重构新格式:

  • 所以我添加了一些属性,然后停止了其中一个节点,会话复制成功。 但是当我用hibernate+spring mvc+spring security将这个配置移到我的应用程序中时,当我尝试登录时,我总是得到异常 我的所有会话对象都实现了可序列化接口,在web.xml中我已经添加了,我尝试过让EntityManager字段瞬态化,但没有帮助。我认为可能是spring试图将一些bean保存到session

  • 我可以使用ISO 4217代码轻松设置货币,例如“USD”。这将使我能够使用抓取美元符号。getSymbol(),但是,我该如何从货币中提取显示名“dollar”? 我有一个微调器,我想用“美元”、“欧元”、“日元”等货币的名称填充。但是,我无法从ISO 4217代码中提取这些名称。这不是很容易吗? 请注意,我不能使用简单的字符串数组来解决这个问题。这是因为我获取了默认的语言环境,并将其货币添加到