Java @自动连线在Spring restful web服务中不工作
我正在使用Struts2+Spring4+Hibernate4和RESTfulWeb服务开发应用程序。我已经在Springbean文件中配置了Hibernate。对于RESTful web服务,我使用Java @自动连线在Spring restful web服务中不工作,java,spring,hibernate,struts2,jersey,Java,Spring,Hibernate,Struts2,Jersey,我正在使用Struts2+Spring4+Hibernate4和RESTfulWeb服务开发应用程序。我已经在Springbean文件中配置了Hibernate。对于RESTful web服务,我使用 <constant name="struts.action.excludePattern" value="/service/.*"/> 这是我的bean映射: @Path("service/account-management&qu
<constant name="struts.action.excludePattern" value="/service/.*"/>
这是我的bean映射:
@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 id="accountService" class="com.xxx.yyy.services.impl.AccountServiceImpl">
<property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</bean>
如果从Spring获取对象,则Autowired可以工作,并且在从上下文获取对象之前,应该将该对象配置为Springbean。要将某个类配置为Springbean,有时只需要放置一些
@Component
注释,并确保扫描该类以查找注释。在您的情况下,@Service
注释更合适
@Service
@Path("service/account-management")
public class AccountServiceImpl implements AccountService {
在applicationContext.xml
中,您应该
<context:component-scan base-package="com.xxx.yyy.services"/>
值得注意的是,Spring3.1引入了LocalSessionFactoryBuilder,它是专门为@Bean方法设计的 在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>
然后在您的方法内部:
Session session = sessionFactory.getCurrentSession();
这不是问题。Spring应该知道您的服务,以便在那里注入一些东西。@Aleksandr M我已经在bean文件中映射了该服务。但同样的事情也在发生。即使是我也无法在“排除”中加载属性文件urls@AleksandrM好的,我已经添加了代码片段。”系统输出打印LN(会话工厂);'打印为null,但在action类中同样可以工作。