3

Выходит ошибка при компиляции ругается на то что не может создать бин ContactDaoImpl потому что в классе UserRole не правильно использован @OneToMany, а это два разных не связанных класса.

Собственно вот эти классы

UserRole

class UserRole {

    @Entity
    @Table(name = "user_roles",
        uniqueConstraints = @UniqueConstraint(
                columnNames = { "role", "username" }))
    public class UserRole{

    private Integer userRoleId;
    private User user;
    private String role;

    public UserRole() {
    }

    public UserRole(User user, String role) {
        this.user = user;
        this.role = role;
    }

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "user_role_id",
            unique = true, nullable = false)
    public Integer getUserRoleId() {
        return this.userRoleId;
    }

    public void setUserRoleId(Integer userRoleId) {
        this.userRoleId = userRoleId;
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "username", nullable = false)
    public User getUser() {
        return this.user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    @Column(name = "role", nullable = false, length = 45)
    public String getRole() {
        return this.role;
    }

    public void setRole(String role) {
        this.role = role;
    }

}

ContactDaoImpl

class ContactDaoImpl {

    @Repository
    public class ContactDAOImpl implements ContactDAO {

    @Autowired
    private SessionFactory sessionFactory;

    public void addContact(Contact contact) {
        sessionFactory.getCurrentSession().save(contact);
    }

    @SuppressWarnings("unchecked")
    public List<Contact> listContact() {
        return sessionFactory.getCurrentSession().createQuery("from Contact").list();
    }

    public void removeContact(Integer id) {
        Contact contact = (Contact) sessionFactory.getCurrentSession().load(
                Contact.class, id);
        if (null != contact) {
            sessionFactory.getCurrentSession().delete(contact);
        }

    }
}

Стектрэйс:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'contactDAOImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public org.hibernate.SessionFactory kz.tanikin.springtest.dao.ContactDAOImpl.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring/data.xml]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class: springtest.domain.User.userRole[springtest.domain.UserRole]

В чем может быть дело? Могу предоставить дополнительную информацию

data.xml

<bean id="userDao" class="kz.tanikin.springtest.dao.UserDaoImpl">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

<bean id="myUserDetailsService"
      class="kz.tanikin.springtest.service.MyUserDetailsService">
    <property name="userDao" ref="userDao" />
</bean>

и выходит ошибка

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.filterChains': Cannot resolve reference to bean 'org.springframework.security.web.DefaultSecurityFilterChain#0' while setting bean property 'sourceList' with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.web.DefaultSecurityFilterChain#0': Cannot create inner bean '(inner bean)#7bd95c47' of type [org.springframework.security.web.authentication.logout.LogoutFilter] while setting constructor argument with key [3]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#7bd95c47': Cannot resolve reference to bean 'org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices#0' while setting constructor argument with key [1]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices#0': Cannot create inner bean '(inner bean)#232efad5' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#232efad5': Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.core.userdetails.UserDetailsService]: Factory method 'cachingUserDetailsService' threw exception; nested exception is org.springframework.context.ApplicationContextException: More than one UserDetailsService registered. Please use a specific Id reference in or elements.

1 ответ 1

3

Spring жалуется на то, что не может создать бин contactDAOImpl. Он не может заинжектить в него sessionFactory. А это у него не получается, потому что он не может создать бин sessionFactory. А это, в свою очередь, происходит из-за некорректного использования аннотации @ManyToOne в классе UserRole. Скорее всего, вы не перечислили класс User в конфиге Hibernate. Или, как вариант, вы пометили класс User аннотацией org.hibernate.annotations.Entity вместо javax.persistence.Entity.

2
  • 1
    @JTan, смотрите последнюю строчку More than one UserDetailsService registered. Please use a specific Id reference in or elements. Спринг подцепил по какой-то причине несколько экземпляров менеджеров пользовательских учеток и не знает, какую использовать.
    – Nofate
    16 сен 2015 в 8:35
  • Хорошо, спасибо
    – J Mas
    16 сен 2015 в 8:58

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.