不要在线程"主要"中工作@Autowired注释异常显示java.lang.NullPointerException

时间:2015-09-02 13:43:30

标签: java spring-data autowired

我正在使用spring数据,我使用@Bean,@ Entity和Main.java创建配置类但是在运行项目时我得到异常:

Exception in thread "main" java.lang.NullPointerException

@Autowired注释无法正常工作!

Main.java

public class Main {

    @Autowired
    private static TodoRepository todoRepository;

    public static void main(String[] args) {
        Todo todo = new Todo();
        todo.setId(1l);
        todo.setTitle("title");
        System.out.println(todoRepository); //null
        todoRepository.save(todo);          //Exception in thread "main" java.lang.NullPointerException
    }
}

上下文类

@Configuration
@EnableJpaRepositories(basePackages = {"repository"},
        entityManagerFactoryRef = "entityManagerFactory",
        transactionManagerRef = "transactionManager")
@EnableTransactionManagement
@PropertySource("classpath:app.properties")
public class PersistenceContext {

    public PersistenceContext() {
    }

    /**
     * The method that configures the datasource bean
     * */

    @Resource
    private Environment env;

    @Bean(destroyMethod = "close")
    DataSource dataSource() {
        HikariConfig dataSourceConfig = new HikariConfig();
        dataSourceConfig.setJdbcUrl(env.getRequiredProperty("db.url"));
        dataSourceConfig.setDriverClassName(env.getRequiredProperty("db.driver"));
        dataSourceConfig.setUsername(env.getRequiredProperty("db.username"));
        dataSourceConfig.setPassword(env.getRequiredProperty("db.password"));
        return new HikariDataSource(dataSourceConfig);
    }

    /**
     * The method that configures the entity manager factory
     * */
    @Bean
    LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, Environment env) {
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setDataSource(dataSource);
        entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        entityManagerFactoryBean.setPackagesToScan("entity");

        Properties jpaProperties = new Properties();

        jpaProperties.put("hibernate.dialect", env.getRequiredProperty("hibernate.dialect"));
        jpaProperties.put("hibernate.hbm2ddl.auto", env.getRequiredProperty("hibernate.hbm2ddl.auto"));
        jpaProperties.put("hibernate.show_sql", env.getRequiredProperty("hibernate.show_sql"));
        jpaProperties.put("hibernate.format_sql", env.getRequiredProperty("hibernate.format_sql"));

        entityManagerFactoryBean.setJpaProperties(jpaProperties);

        return entityManagerFactoryBean;
    }

    /**
     * The method that configures the transaction manager
     * */
    @Bean
    JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory);
        return transactionManager;
    }
}

存储库

public interface TodoRepository extends CrudRepository<Todo, Long> {

}

堆栈跟踪

null
Exception in thread "main" java.lang.NullPointerException
    at Main.main(Main.java:28)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)

Process finished with exit code 1

1 个答案:

答案 0 :(得分:0)

您的主类不是托管的spring bean。您需要创建一个ApplicationContext,见下文:

public class Main {
    public static void main(String[] args) {public static void main(String[] args) {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(PersistenceContext.class);
        TodoRepository todoRepository = ctx.getBean(TodoRepository.class);
        Todo todo = new Todo();
        todo.setId(1l);
        todo.setTitle("title");
        System.out.println(todoRepository); // not null
        todoRepository.save(todo);
    }
}