@Autowired SessionFactory在Java配置中返回null spring

时间:2016-12-24 14:17:52

标签: java spring spring-mvc nullpointerexception

当我尝试在sessionFactory中使用DI时,我在sessionFactory中有空指针异常我必须将spring 3项目转换为没有xml的Spring 4。我不知道我面临的问题是什么,SessionFactory根本没有自动装配。当我尝试测试案例泛型doa添加方法

这是我的bean配置文件

@Configuration
@EnableTransactionManagement
@EnableWebMvc
@ComponentScan(basePackages = "io.github.bibekshakya35.ehealth")
public class EhealthCofiguration {

@Bean
public ViewResolver getViewResolver() {
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setViewClass(JstlView.class);
    viewResolver.setPrefix("/WEB-INF/view/");
    viewResolver.setSuffix(".jsp");
    return viewResolver;
}

@Bean(name = "dataSource")
public javax.sql.DataSource getDataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName("org.postgresql.Driver");
    dataSource.setUrl("jdbc:postgresql://localhost:5432/ehealth");
    dataSource.setUsername("test");
    dataSource.setPassword("test123");
    return dataSource;
}

@Autowired
@Bean(name = "sessionFactory")
public SessionFactory getSessionFactory(javax.sql.DataSource dataSource) {
    LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
    sessionBuilder.scanPackages("io.github.bibekshakya35.ehealth.model");
    sessionBuilder.addProperties(getHibernateProperties());
    return sessionBuilder.buildSessionFactory();
}

private Properties getHibernateProperties() {
    Properties properties = new Properties();
    properties.put("hibernate.show_sql", "true");
    properties.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
    properties.put("hibernate.hbm2ddl.auto", "update");
    return properties;
}

@Autowired
@Bean(name = "transactionManager")
public HibernateTransactionManager getTransactionManager(
        SessionFactory sessionFactory) {
    HibernateTransactionManager transactionManager = new HibernateTransactionManager(
            sessionFactory);

    return transactionManager;
}
}

加载我创建的这个类

public class EhealthWebAppIntializer implements WebApplicationInitializer {

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
    applicationContext.register(EhealthCofiguration.class);
    ServletRegistration.Dynamic dispatcher =servletContext.addServlet("SpringDispatcher", new DispatcherServlet(applicationContext));
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/");
}

}

这是我的通用doa类,当我尝试访问sessionFactory.getCurrentSession(); NPE时,我会注入SessionFactory,

@Repository
@Transactional
public class HibernateDAO<T extends Serializable> implements IGenericDao<T> {

private Class<T> clazz;

Session session;

@Autowired
SessionFactory sessionFactory;

private static final Logger LOG = Logger.getLogger(HibernateDAO.class.getName());

@Override
public void setClazz(Class<T> clazzToSet) {
    this.clazz = clazzToSet;
}

@Override
public void create(T entity) {
    session = getCurrentSession();
    LOG.log(Level.INFO, "inside create entity and you just bind your session to the current one{0}", session.toString());
    session.saveOrUpdate(entity);
    LOG.info("saved");
    session.flush();
    session.refresh(entity);
}



protected Session getCurrentSession() {
    return sessionFactory.getCurrentSession();
}  
}

这是NPE的堆栈跟踪

Exception in thread "main" java.lang.NullPointerException
at io.github.bibekshakya35.ehealth.DAO.genericdao.HibernateDAO.getCurrentSession(HibernateDAO.java:115)
at io.github.bibekshakya35.ehealth.DAO.genericdao.HibernateDAO.create(HibernateDAO.java:85)
at io.github.bibekshakya35.ehealth.service.impl.user.main(user.java:46)

这是我的用户实体

@Entity

@Table(name =“users”) public class User实现Serializable,AbstractEntity {

@Id
@Column(name = "username",unique = true)
private String userName;

@NotNull(message = "password cannot be empty")
@Column(name = "users_password")
private String userPassword;

@Embedded
private UserProfile userProfile;

@Embedded
private AuditInfo auditInfo;

@Enumerated(EnumType.STRING)
private UserType userType;

@Column(name = "is_active")
private boolean active = true;

//getter n setter

}

1 个答案:

答案 0 :(得分:1)

在聊天中,您向我提供了此代码:

 public static void main(String[] args) {
     User user = new User();
     IGenericDao<User> iGenericDao = new HibernateDAO<>();
     user.setUserName("bibekshakya35");
     user.setUserPassword("ros3");
     user.setUserType(UserType.GUEST);
     user.setActive(true);
     UserProfile userProfile = new UserProfile();
     userProfile.setAge(21);
     userProfile.setBasicInfo("kdhsa");
     userProfile.setEmailId("dsadas@gmail.com");
     userProfile.setUserGender(UserGender.Male);
     userProfile.setFullname("bibek shakya");
     userProfile.setMobileNumber("45454545");
     userProfile.setLandLineNumber("445444");
     userProfile.setUserProfilePic("index.jsp");
     user.setUserProfile(userProfile);
     AuditInfo auditInfo = new AuditInfo();
     auditInfo.setCreatedOn(new Date());
     auditInfo.setModifiedOn(new Date());
     auditInfo.setVerifiedOn(new Date());
     user.setAuditInfo(auditInfo);
     iGenericDao.create(user);
   }

错误原因:
在您创建新的HibernateDAO实例时,如此IGenericDao<User> iGenericDao = new HibernateDAO<>();这就是问题所在。

如果您正在使用注释,手动创建新实例,通常会导致上述错误。
错误原因:
Spring只能自动装配它管理的bean;如果你自己调用new来创建一个bean,那么@Autowired字段就不会被填充(并且不会调用@PostConstruct之类的方法)。

解决方案:
您需要将@autowired添加到HibernateDAO@Autowired将使用包含真实@Controller SessionFactory的确切类来实例化它。

实施例
通常我们在类中使用@Service@Controller @RequestMapping(value="/someURL") public class mainClass { @Autowired HibernateDAO abc; //Code (methods) to test Your CRUD Operations } 等注释进行注释。
像这样

plugins: [
   new webpack.LoaderOptionsPlugin({
     test: /\.js$/,
     options: {
       eslint: {
         // options
       }
     }
   })
]