我正在用Struts2 + Spring4 + Hibernate4和RESTful web服务开发应用程序。我在Spring文件中配置了Hibernate。对于RESTful web服务,我已经将struts.xml中的URL排除在
<constant name="struts.action.excludePattern" value="/service/.*"/> 如果我在任何动作类中访问sessionFactory对象,它就能正常工作。但是如果我在我的web服务中访问它,它就会给NullPointerException。
在Google上搜索之后,我发现如果我们绕过Struts的URL,就不允许使用@Autowired注释初始化对象。
怎么解决这件事?我在谷歌上搜索过,但没有发现任何有用的东西。
这是我的服务:
@Path("service/account-management")
public class AccountServiceImpl implements AccountService {
@Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
@POST
@PermitAll
@Path("/accounts")
public Response getAllAccounts() {
System.out.println(sessionFactory);
Session session = this.sessionFactory.getCurrentSession();
List<VbarAccount> personList = session.createQuery("from TEST").list();
System.out.println(personList);
session.close();
return Response.status(200).build();
}
}这是我的bean映射:
<bean id="accountService" class="com.xxx.yyy.services.impl.AccountServiceImpl">
<property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</bean>发布于 2015-08-06 12:11:12
如果从Spring获得对象,并且在从上下文中获得对象之前,应该将该对象配置为Spring,则自动配置可以工作。要将某些类配置为Spring,有时只需要添加一些@Component注释,并确保对类进行注释扫描。在这种情况下,使用@Service注释更合适。
@Service
@Path("service/account-management")
public class AccountServiceImpl implements AccountService { 在applicationContext.xml中你应该有
<context:component-scan base-package="com.xxx.yyy.services"/>发布于 2021-03-11 05:11:16
值得一提的是,Spring3.1引入了LocalSessionFactoryBuilder,这是专门为@Bean方法中使用而设计的。
http://static.springsource.org/spring/docs/3.1.0.RC1/javadoc-api/org/springframework/orm/hibernate4/LocalSessionFactoryBuilder.html
在XML中,还可以使用hibernate配置:
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="yourGivenName">
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>或者可以使用基于java的bean配置:@Bean公共SessionFactory sessionFactory(){ AnnotationSessionFactoryBean sessionFactoryBean =新AnnotationSessionFactoryBean();sessionFactoryBean.setConfigLocation(新ClassPathResource("hibernate.cfg.xml"));sessionFactoryBean.afterPropertiesSet();返回sessionFactoryBean.getObject();}
然后您可以在Spring中使用它:
@Autowired
SessionFactory sessionFactory;然后在你的方法里面:
Session session = sessionFactory.getCurrentSession();https://stackoverflow.com/questions/31854715
复制相似问题