[英]@Autowired not working in Spring restful web service
我正在使用 Struts2 + Spring4 + Hibernate4 和 RESTful Web 服務開發應用程序。 我已經在 Spring bean 文件中配置了 Hibernate。 對於 RESTful Web 服務,我使用了struts.xml
URL
<constant name="struts.action.excludePattern" value="/service/.*"/>
如果我在任何操作類中訪問sessionFactory
對象,它就可以正常工作。 但是如果我在我的網絡服務中訪問它,它會給出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>
如果您從 Spring 獲取對象,則 Autowired 可以工作,並且在從上下文獲取對象之前,應將對象配置為 Spring bean。 將某個類配置為 Spring bean 有時只需要放置一些@Component
注解並確保掃描該類以查找注解。 在你的情況下, @Service
注釋更合適
@Service
@Path("service/account-management")
public class AccountServiceImpl implements AccountService {
在applicationContext.xml
你應該有
<context:component-scan base-package="com.xxx.yyy.services"/>
值得注意的是,Spring 3.1 引入了 LocalSessionFactoryBuilder,它是專門為在 @Bean 方法中使用而設計的。
在您的 XML 中,您還可以使用休眠配置:
<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 public SessionFactory sessionFactory(){ AnnotationSessionFactoryBean sessionFactoryBean = new AnnotationSessionFactoryBean(); sessionFactoryBean.setConfigLocation(new ClassPathResource("hibernate.cfg.xml")); sessionFactoryBean.afterPropertiesSet(); 返回 sessionFactoryBean.getObject(); }
然后你可以在你的 Spring bean 中使用它:
@Autowired
SessionFactory sessionFactory;
然后在你的方法里面:
Session session = sessionFactory.getCurrentSession();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.