简体   繁体   English

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

[英]@Autowired SessionFactory returning null spring in Java configuration

I m having null pointer exception in sessionFactory when i try to use DI in sessionFactory I have to turn spring 3 project into Spring 4 with no xml.当我尝试在 sessionFactory 中使用 DI 时,我在 sessionFactory 中遇到空指针异常我必须将 spring 3 项目转换为没有 xml 的 Spring 4。 I dont know what the problem im facing, SessionFactory doesnot autowired at all.我不知道我面临什么问题,SessionFactory 根本没有自动装配。 when i try to test case generic doa Add Method当我尝试测试用例通用 doa 添加方法时

here is my Configuration File for bean这是我的 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;
}
}

to load this class i have created加载我创建的这个类

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("/");
}

}

this is my generic doa class where im injecting SessionFactory when it try to access sessionFactory.getCurrentSession();这是我的通用 doa 类,当它尝试访问sessionFactory.getCurrentSession();时,我会在其中注入 SessionFactory sessionFactory.getCurrentSession(); NPE is occur, NPE 发生,

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

Here is my stack trace for NPE这是我的 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)

here is my user entity这是我的用户实体

@Entity
@Table(name = "users")
public class User implements 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

}

In chat, You provided me with this code :在聊天中,您向我提供了以下代码:

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

Cause of error:错误原因:
As You are creating the new HibernateDAO instance like this当您像这样创建新的HibernateDAO实例时
IGenericDao<User> iGenericDao = new HibernateDAO<>();
This is creating the problem.这就造成了问题。

In the case where You are using annotations, creating new instance manually ,usually causes the above mentioned error.在您使用注解的情况下,手动创建新实例通常会导致上述错误。
Reason of error:错误原因:
Spring can only autowire beans that it manages; Spring 只能自动装配它管理的 bean; if you call new to create a bean yourself, @Autowired fields don't get filled in (and methods like @PostConstruct aren't called).如果您调用 new 自己创建一个 bean,@Autowired 字段不会被填充(并且不会调用 @PostConstruct 之类的方法)。

Solution:解决方案:
You need to add @autowired to the HibernateDAO which will instantiate it with the exact class which includes the real @Autowired SessionFactory.您需要将@autowired添加到HibernateDAO ,它将使用包含真正的@Autowired SessionFactory 的确切类实例化它。

Example :示例
Usually we do it in the class which is itself annotated with annotations like @Controller or @Service .通常我们在类中这样做,该类本身用@Controller@Service之类的注解进行注解。
Like this像这样

@Controller
@RequestMapping(value="/someURL")
public class mainClass {
    @Autowired
    HibernateDAO abc;
    //Code (methods) to test Your CRUD Operations
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM