当前位置: 首页 > 知识库问答 >
问题:

创建名为“managedBeanClass”的bean时出错:通过字段“person”表示的未满足的依赖关系:

顾斌
2023-03-14

我是sping-mvc的新手。我试图找到使用sping-mvc、hiberNate、mysql和jsf开发测试项目的好教程。最后我创建了示例项目。

我的第一个问题是,

就是这个Spring-mvc结构

但不幸的是,上面显示的是错误。

应用程序上下文。xml

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

        <context:annotation-config />

        <beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
            <beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
            <beans:property name="url"
                value="jdbc:mysql://localhost:3306/vehicles" />
            <beans:property name="username" value="root" />
            <beans:property name="password" value="root" />
        </beans:bean> 

        <!-- Hibernate 4 SessionFactory Bean definition -->
        <beans:bean id="hibernate4AnnotatedSessionFactory"
            class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
            <beans:property name="dataSource" ref="dataSource" />
            <beans:property name="annotatedClasses">
                <beans:list>
                    <beans:value>com.journaldev.springhibernate.model.Person</beans:value>
                </beans:list>
            </beans:property>
            <beans:property name="hibernateProperties">
                <beans:props>
                    <beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
                    </beans:prop>
                    <beans:prop key="hibernate.show_sql">true</beans:prop>
                </beans:props>
            </beans:property>
        </beans:bean>



        <context:component-scan base-package="com.journaldev" />

        <tx:annotation-driven transaction-manager="transactionManager" />

        <beans:bean id="transactionManager"
            class="org.springframework.orm.hibernate4.HibernateTransactionManager">
            <beans:property name="sessionFactory"
                ref="hibernate4AnnotatedSessionFactory" />
        </beans:bean>

</beans:beans>

人脸配置。xml

<?xml version="1.0" encoding="UTF-8"?>
<faces-config version="2.2"
              xmlns="http://xmlns.jcp.org/xml/ns/javaee"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
              http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">

    <application>
        <el-resolver>
            org.springframework.web.jsf.el.SpringBeanFacesELResolver
        </el-resolver>
    </application>

</faces-config>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">

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

    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Development</param-value>
    </context-param>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>/test/*</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>

</web-app>

个人类

@Entity
@Table(name="PERSON")
public class Person {
@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;

@Column(name="name")
private String name;

@Column(name="country")
private String country;

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getCountry() {
    return country;
}

public void setCountry(String country) {
    this.country = country;
}

@Override
public String toString(){
    return "id="+id+", name="+name+", country="+country;
}
}

PersonDAOImpl类

@Repository
public class PersonDAOImpl implements PersonDAO{

private static final Logger logger = 
LoggerFactory.getLogger(PersonDAOImpl.class);

private SessionFactory sessionFactory;

public void setSessionFactory(SessionFactory sf){
    this.sessionFactory = sf;
}

@Override
public void addPerson(Person p) {
    Session session = this.sessionFactory.getCurrentSession();
    session.persist(p);
    logger.info("Person saved successfully, Person Details="+p);
}

}

个人服务Impl类

@Service
public class PersonServiceImpl implements PersonService {

@Autowired
private PersonDAO personDAO;

@Override
@Transactional
public void addPerson(Person p) {
    personDAO.addPerson(p);
}
}

ManagedBeanClass类

@ManagedBean("managedBeanClass")
@ViewScoped
public class ManagedBeanClass implements Serializable{

@Autowired
private Person person;

@Autowired
private PersonService personServiceImpl;

public void addPersion(){
    personServiceImpl.addPerson(person);

}

public Person getPerson() {
    return person;
}

public void setPerson(Person person) {
    this.person = person;
}

}

错误是,

WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'managedBeanClass': Unsatisfied dependency expressed through field 'person': No qualifying bean of type [com.journaldev.springhibernate.model.Person] found for dependency [com.journaldev.springhibernate.model.Person]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.journaldev.springhibernate.model.Person] found for dependency [com.journaldev.springhibernate.model.Person]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
Aug 28, 2017 5:04:46 PM org.springframework.web.context.ContextLoader initWebApplicationContext
SEVERE: Context initialization failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'managedBeanClass': Unsatisfied dependency expressed through field 'person': No qualifying bean of type [com.journaldev.springhibernate.model.Person] found for dependency [com.journaldev.springhibernate.model.Person]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.journaldev.springhibernate.model.Person] found for dependency [com.journaldev.springhibernate.model.Person]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:569)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:349)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:776)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4853)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5314)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.journaldev.springhibernate.model.Person] found for dependency [com.journaldev.springhibernate.model.Person]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1406)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1057)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1019)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:566)
    ... 24 more

请给我一个答案。我很久以前就试过了。我可以使用spring构建项目。但是我需要用@Autowired注解构建spring mvc

共有1个答案

晏卓君
2023-03-14

在ManagedBeanClass类中,您尝试自动关联实体。实体不是自动连线候选对象。

把班级改成

@Autowired
private Person person;

       to 

private Person person = new Person();

是的,您可以使用@Autowire让spring创建实体的原型范围实例。但它是脏的,因为实体既不是ManagedBeanClass的依赖项,也不是ManagedBeanClass的上下文,该实体是ManagedBeanClass的模型。模型不是依赖项,因为ManagedBean类必须能够自己创建模型,而不是让spring来处理它。

不管怎样,你喜欢这个肮脏的解决方案。

假设实体在com的包中。journaldev,将以下内容添加到实体中:

@Bean                                                         <-new
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)               <-new 

@Entity
@Table(name="PERSON")
public class Person {
 类似资料: