2013-07-21 8 views
1

Я использую JPA, eclispelink и пружину 3. У меня есть интерфейс UserDAO:
@Override и @Transactional аннотаций

public interface UserDAO { 
    public void saveUser(User user); 
    } 

и класс реализации:

@Service 
@Transactional 
public class UserDAOImpl implements UserDAO{ 

@PersistenceContext 
EntityManager em; 

@Override 
public void saveUser(User user) { 
    em.persist(user); 
} 


Когда я начинаю приложение I имеют погрешность:

HTTP Status 500 - Servlet.init() for servlet appServlet threw exception<br> 
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cartController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: foo.endpoints.UserEndpoint foo.controller.CartController.userEndpoint; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userEndpoint': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: foo.dao.UserDAOImpl foo.endpoints.UserEndpoint.userDAO; nested exception is java.lang.IllegalArgumentException: Can not set foo.dao.UserDAOImpl field foo.endpoints.UserEndpoint.userDAO to com.sun.proxy.$Proxy16 

org.springframework.beans.factory.BeanCreationException: Could not autowire field: foo.endpoints.UserEndpoint foo.controller.CartController.userEndpoint; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userEndpoint': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: foo.dao.UserDAOImpl foo.endpoints.UserEndpoint.userDAO; nested exception is java.lang.IllegalArgumentException: Can not set foo.dao.UserDAOImpl field foo.endpoints.UserEndpoint.userDAO to com.sun.proxy.$Proxy16 


, но если я не реализует интерфейс:

@Service 
@Transactional 
public class UserDAOImpl { 
@PersistenceContext 
EntityManager em; 
    public void saveUser(User user) { 
    em.persist(user); 
    } 


все работает нормально. Я этого не понимаю. Может быть, это что-то с методом @Override? Благодаря

+2

Я уверен, что есть некоторые точные дубликаты вопроса http://stackoverflow.com/a/8224772/241986, в основном стратегия Spring по умолчанию заключается в использовании прокси-сервера JDK, если класс реализует хотя бы один интерфейс и CGLIB прокси в противном случае. Когда используется прокси-сервер JDK, вы не сможете вводить класс, будет доступен только интерфейс. –

+1

BTW, я думаю, что соглашение состоит в том, чтобы комментировать классы DAO с '@ Repository', а не' @ Service' – Mina

+0

@BorisTreukhov точно проблема! Я искал эту странную проблему так долго –

ответ

4

Если вы определяете интерфейс для бина, то вы должны вводить экземпляр интерфейса, а не экземпляр конкретного класса:

@Autowired 
private UserDAO userDAO; 

и не

@Autowired 
private UserDAOImpl userDAOImpl; 

Поскольку фактический экземпляр bean - это динамический прокси JDK, который реализует интерфейс и вызывает вашу реализацию. Это не экземпляр UserDAOImpl.

+0

Я считаю, что вторая часть кода должна быть 'private UserDAOImpl userDAOImpl;' правильно? –

+0

Да. Извините за эту ошибку. –

Смежные вопросы