使用Jersey和Spring进行REST服务的@Autowired属性的NullPointerException
我一直在开发一个gwt应用程序,应该有一个rest服务来访问数据库,包括它自己的数据库和其他远程数据库。 我使用Spring来更好地使用数据库(objectdb)而不是我在使用Jersey进行练习。 这是给出问题的代码:
User.java
@Entity @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS) @XmlRootElement public class User implements java.io.Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private long id; private String name; private String surname; private int age; ... }
Customer.java
@Entity @XmlRootElement public class Customer extends User implements java.io.Serializable{ private static final long serialVersionUID = 1L; @Column(unique=true) private String fiscalCode; @Column(unique=true) private String docNumber; ... }
CustomerDAO.java
@Repository("customerDAO") public class CustomerDAO extends JpaDAO { ... }
JpaDAO.java
public abstract class JpaDAO { protected Class entityClass; @PersistenceContext(unitName = "MyPersistenceUnit") protected EntityManager em; @SuppressWarnings("unchecked") public JpaDAO() { ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass(); this.entityClass = (Class) genericSuperclass.getActualTypeArguments()[0]; } public List findAll() { TypedQuery q = em.createQuery( "SELECT h FROM " + entityClass.getName() + " h", entityClass); return q.getResultList(); }
最后是CustomerServiceImpl.java
@Service("customerService") @Path("/customers") public class CustomerServiceImpl implements CustomerService { @Autowired private CustomerDAO customerDAO; @Override @GET @Produces({MediaType.APPLICATION_XML}) public List findAll() { return customerDAO.findAll(); } }
正确编写了web.xml。 当我表演
http://127.0.0.1/rest/customers
看来customerDAO为null,导致exception…
你能帮我吗?
这是web.xml
RONF.html org.springframework.web.context.ContextLoaderListener springGwtRemoteServiceServlet org.spring4gwt.server.SpringGwtRemoteServiceServlet springGwtRemoteServiceServlet /ronf/ronfServices/* Jersey com.sun.jersey.spi.container.servlet.ServletContainer com.sun.jersey.config.property.packages it.unibo.ronf.server.services 1 Jersey /rest/* com.sun.jersey.contribs jersey-spring ${jersey.version}
这是applicationContext.xml
您尚未在applicationContext.xml文件中为customerDAO
创建bean。 如果要在CustomerServiceImpl.java
中将其用作bean,请在applicationContext.xml中创建其bean。
将以下代码放在applicationContext.xml中:
并在CustomerServiceImpl.java
类上添加@Component
注释。
这应该适合你。 作为参考,您可以使用本教程。 在这里,您可以更好地了解弹簧和JAX-RS的集成。