복붙노트

[SPRING] Jersey 및 Spring for REST 서비스의 @Autowired 속성에 대한 NullPointerException

SPRING

Jersey 및 Spring for REST 서비스의 @Autowired 속성에 대한 NullPointerException

나는 데이터베이스와 자체 데이터베이스 및 다른 원격 데이터베이스에 액세스 할 수있는 휴식 서비스가 있어야하는 gwt 응용 프로그램을 개발해 왔습니다. 나는 데이터베이스 (objectdb)로 더 잘 작업하기 위해 Spring을 사용하고 저지에서 연습하지는 않았다. 문제를 일으키는 코드는 다음과 같습니다.

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<Customer> {
...
}

JpaDAO.java

public abstract class JpaDAO<E> {
protected Class<E> entityClass;

@PersistenceContext(unitName = "MyPersistenceUnit")
protected EntityManager em;

@SuppressWarnings("unchecked")
public JpaDAO() {
 ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
 this.entityClass = (Class<E>) genericSuperclass.getActualTypeArguments()[0];
}

public List<E> findAll() {
    TypedQuery<E> 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<Customer> findAll() {
    return customerDAO.findAll();
 }
}

web.xml이 올바르게 작성됩니다. 수행 할 때

http://127.0.0.1/rest/customers

그것은 customerDAO null이며 그 예외가 발생할 것 ...

도울 수 있니?

여기에 web.xml이 있습니다.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
          http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5" xmlns="http://java.sun.com/xml/ns/javaee">

<!-- Servlets -->

<!-- Default page to serve -->
<welcome-file-list>
    <welcome-file>RONF.html</welcome-file>
</welcome-file-list>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>


<servlet>
    <servlet-name>springGwtRemoteServiceServlet</servlet-name>
    <servlet-class>org.spring4gwt.server.SpringGwtRemoteServiceServlet</servlet-class>
</servlet>


<servlet-mapping>
    <servlet-name>springGwtRemoteServiceServlet</servlet-name>
    <url-pattern>/ronf/ronfServices/*</url-pattern>
</servlet-mapping>

<servlet>
    <servlet-name>Jersey</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
      <param-name>com.sun.jersey.config.property.packages</param-name>
      <param-value>it.unibo.ronf.server.services</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>Jersey</servlet-name>
    <url-pattern>/rest/*</url-pattern>
</servlet-mapping>

<dependency>
    <groupId>com.sun.jersey.contribs</groupId>
    <artifactId>jersey-spring</artifactId>
    <version>${jersey.version}</version>
</dependency>

</web-app>

여기에는 applicationContext.xml이 있습니다.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">

<context:component-scan base-package="it.unibo.ronf"/>

<context:annotation-config/>

<task:annotation-driven executor="myExecutor" scheduler="myScheduler"/>

<task:executor id="myExecutor" pool-size="5"/>

<task:scheduler id="myScheduler" pool-size="10"/>

<tx:annotation-driven/>

<bean class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean" id="entityManagerFactory">
    <property name="persistenceUnitName" value="MyPersistenceUnit"/>
</bean>

<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>

</beans>

해결법

  1. ==============================

    1.applicationContext.xml 파일에 customerDAO 용 bean을 만들지 않았습니다. 이것을 CustomerServiceImpl.java에서 bean으로 사용하려면 applicationContext.xml에 bean을 작성하십시오.

    applicationContext.xml 파일에 customerDAO 용 bean을 만들지 않았습니다. 이것을 CustomerServiceImpl.java에서 bean으로 사용하려면 applicationContext.xml에 bean을 작성하십시오.

    applicationContext.xml에 아래 코드를 입력하십시오.

    <bean class="name.of.package.CustomerDAO" id="customerDAO">
    </bean>
    

    그리고 CustomerServiceImpl.java 클래스에 @Component 어노테이션을 추가하십시오.

    이것은 당신을 위해 작동해야합니다. 참고로이 자습서를 사용할 수 있습니다. 여기에서는 스프링과 JAX-RS의 통합을 더 잘 이해할 수 있습니다.

  2. from https://stackoverflow.com/questions/16770955/nullpointerexception-on-autowired-attribute-with-jersey-and-spring-for-rest-ser by cc-by-sa and MIT license