0

我正在编写一个将使用 Spring、Hibernate 等的 Java 应用程序,它将被打包在一个 Jar 中并从类似的命令运行。

我的主要课程现在如下所示:

public class App
{

    private static final Logger logger = LoggerFactory.getLogger(App.class);


    @Autowired
    private static MemberInquiryService memberInquiryService;


    public static void main(String[] args )
    {
        logger.info("Starting Inquiry Batch Process");

        int pendingRecords = memberInquiryService.getPendingRecordCount();

        logger.info("Current Number Of Pendinig Records (" + pendingRecords + ")");

        logger.info("Ending Inquiry Batch Process");
    }
}

在 getPendingRecordCount 我只是返回“10”进行测试:

public int getPendingRecordCount()
    {


        return 10;
    };

为什么我会收到以下错误:

Exception in thread "main" java.lang.NullPointerException
    at org.XXXX.inquirybatch.app.App.main(App.java:33)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

这也是我的 DatabaseConfig.class

@Configuration
@EnableTransactionManagement
@ComponentScan(basePackages= { "org.xxxx.inquirybatch", "org.xxxx.core" })
@PropertySource("classpath:application.properties")
public class DatabaseConfig  {


    private static final Logger logger = LoggerFactory.getLogger(DatabaseConfig.class);

    @Autowired
    Environment env;

    @Bean
     public DataSource dataSource()  {

        String serverType = env.getProperty("server.type");

        try {

            if(serverType.equalsIgnoreCase("tomcat"))
            {
                com.mchange.v2.c3p0.ComboPooledDataSource ds = new com.mchange.v2.c3p0.ComboPooledDataSource();

                ds.setDriverClass(env.getProperty("database.driver"));
                ds.setUser(env.getProperty("database.user"));
                ds.setPassword(env.getProperty("database.password"));
                ds.setJdbcUrl(env.getProperty("database.url"));

                return ds;
            }
            else
            {
                Context ctx = new InitialContext();
                return (DataSource) ctx.lookup("java:jboss/datasources/mySQLDB");
            }
        }
        catch (Exception e)
        {
                  logger.error(e.getMessage());
        }

        return null;
     }

    @Bean
    public SessionFactory sessionFactory()
    {

        LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
        factoryBean.setDataSource(dataSource());
        factoryBean.setHibernateProperties(getHibernateProperties());
        factoryBean.setPackagesToScan(new String[] { "org.xxxx.inquirybatch.model", "org.xxxx.core.model" } );

        try {
            factoryBean.afterPropertiesSet();
        } catch (IOException e) {
            logger.error(e.getMessage());
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }


        return factoryBean.getObject();
    }

    @Bean
    public Properties getHibernateProperties()
    {
        Properties hibernateProperties = new Properties();

        hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
        hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
        hibernateProperties.setProperty("hibernate.use_sql_comments", env.getProperty("hibernate.use_sql_comments"));
        hibernateProperties.setProperty("hibernate.format_sql", env.getProperty("hibernate.format_sql"));
        hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));

        hibernateProperties.setProperty("hibernate.generate_statistics", env.getProperty("hibernate.generate_statistics"));




        hibernateProperties.setProperty("javax.persistence.validation.mode", env.getProperty("javax.persistence.validation.mode"));

        //Audit History flags
        hibernateProperties.setProperty("org.hibernate.envers.store_data_at_delete", env.getProperty("org.hibernate.envers.store_data_at_delete"));
        hibernateProperties.setProperty("org.hibernate.envers.global_with_modified_flag", env.getProperty("org.hibernate.envers.global_with_modified_flag"));

        return hibernateProperties;
    }

    @Bean
    public HibernateTransactionManager hibernateTransactionManager()
    {
        HibernateTransactionManager htm = new HibernateTransactionManager();
        htm.setSessionFactory(sessionFactory());
        htm.afterPropertiesSet();
        return htm;
    }

}
4

3 回答 3

0

Spring 从不注入静态字段。它只注入从应用程序上下文中检索到的对象,或者它们本身被注入到其他对象中。

您甚至没有在您的程序中创建应用程序上下文,因此 Spring 在该程序中不扮演任何角色。

我建议阅读文档

于 2013-04-05T17:11:09.037 回答
0

您需要从 ClassPathXmlApplicationContext 获取 memberInquiryService

例如 :-

ApplicationContext context= new ClassPathXmlApplicationContext("spring config.xml");
MmberInquiryService memberInquiryService = context.getBean("memberInquiryService ");

基本上在您的代码片段中 MemberInquiryService 不是弹簧管理的,因为您不是从弹簧容器中获取的。您还需要在 spring config.xml 中声明 MmberInquiryService 条目

于 2013-04-05T17:13:48.623 回答
0

我不得不将主要课程更改为..

public static void main(String[] args )
    {
        logger.info("Starting Inquiry Batch Process");

        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

        MemberInquiryService memberInquiryService = (MemberInquiryService) context.getBean("memberInquiryService");

        int pendingRecords = memberInquiryService.getPendingRecordCount();

        logger.info("Current Number Of Pendinig Records (" + pendingRecords + ")");

        logger.info("Ending Inquiry Batch Process");
    }
于 2013-04-05T17:34:46.303 回答