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

创建Bean时出错。自动连线依赖项注入失败。无法自动连线字段

傅恺
2023-03-14

我在Spring+SpringMVC+Hibernate+MySQL web应用程序中的Spring配置有一个问题。Spring无法创建我在Service类中宣布的bean。

下面是Controller类

@Controller
@RequestMapping("/main")
public class MainController {

private static Logger LOGGER = Logger.getLogger("Controller");

@Autowired
private PersonServiceImpl personServiceImpl;

@Autowired
private ActionServiceImpl actionServiceImpl;



@RequestMapping(value = "/users" , method = RequestMethod.GET)
public String getUsers(Model model) {

    LOGGER.debug("Receive request for show all users");
    List<User> users = personServiceImpl.getAll();
    model.addAttribute("users", users);
    return "userspage";

}

@RequestMapping(value = "/users/add", method = RequestMethod.GET)
public String getAdd() {

    LOGGER.debug("Receive request to show add page");
    return "addpage";

}

@RequestMapping(value = "/users/add", method = RequestMethod.POST)
public String add(@ModelAttribute("userAttribute") User user,Actions 
actions) {

    LOGGER.debug("Recieve request to add a new user");
    personServiceImpl.add(user);
    actionServiceImpl.addAction(user.getId(), actions);
    return "addedpage";

}

@RequestMapping(value = "/users/delete", method = RequestMethod.GET)
public String delete(@RequestParam(value = "id", required = true)Integer 
id, Model model) {

    LOGGER.debug("Recieve request for deleting user");
    personServiceImpl.delete(id);
    model.addAttribute("id", id);
    return "deletedpage";

}

@RequestMapping(value = "/users/edit", method = RequestMethod.GET)
public String getEdit(@RequestParam(value = "id", required = true)Integer 
id, Model model) {

    LOGGER.debug("Recieve request to show editpage");
    model.addAttribute("userAttribute", personServiceImpl.get(id));
    return "editpage";

}

@RequestMapping(value = "/users/edit", method = RequestMethod.POST)
public String saveEdit(@ModelAttribute("userAttribute") User user,
                       @RequestParam(value = "id", required = 
true)Integer id, Model model,
                       Actions actions) {

    LOGGER.debug("Received request to update person");
    user.setId(id);
    personServiceImpl.edit(user);
    actionServiceImpl.editAction( id, actions);
    model.addAttribute("id", id);
    return "editedpage";

}

@RequestMapping(value = "/users/actions", method = RequestMethod.GET)
public String getActionsOfUser(@RequestParam(value = "id", required = 
true)Integer id, Model model,

    LOGGER.debug("Recieve request to show user Action");
    model.addAttribute("userId", personServiceImpl.get(id));
    model.addAttribute("userAction", 
actionServiceImpl.getListOfActions(user));
    return "userActionsPage";

}
}
public interface ActionService {

List<Actions> getListOfActions(User user);

void addAction(Integer id, Actions actions);

void editAction(Integer id, Actions actions);

}



public interface PersonService {

List<User> getAll();

User get(Integer id);

void add(User user);

void delete(Integer id);

void edit(User user);

}
@Service
@Transactional
public class ActionServiceImpl implements ActionService {

private static Logger LOGGER = Logger.getLogger("actionService");

@Autowired
private SessionFactory sessionFactory;

@Bean
ActionService getActionService() {
    return new ActionServiceImpl();
}

public List<Actions> getListOfActions(User user){

    LOGGER.debug("Retriving all user actions");
    Session session = sessionFactory.getCurrentSession();
    Query query = session.createQuery("from Actions where  user = " +    
user.getId());
    return query.list();
}

public void addAction(Integer id, Actions actions){

    LOGGER.debug("Adding addAction to user info");
    Session session = sessionFactory.getCurrentSession();
    actions.setActionType(ActionType.ADDING_NEW_USER);
    actions.setDate(new Date());
    User existingUser = (User) session.get(User.class , id);
    actions.setUser(existingUser);
    existingUser.getActions().add(actions);
    session.save(existingUser);
    session.save(actions);

}

public void editAction(Integer id, Actions actions){

    LOGGER.debug("Adding editAction to user info");
    Session session = sessionFactory.getCurrentSession();
    actions.setActionType(ActionType.EDITING_EXISTING_USER);
    actions.setDate(new Date());
    User existingUser = (User) session.get(User.class , id);
    actions.setUser(existingUser);
    existingUser.getActions().add(actions);
    session.save(existingUser);
    session.save(actions);

}
}


@Service
@Transactional
public class PersonServiceImpl implements  PersonService{

private static Logger LOGGER = Logger.getLogger("service");

@Autowired
private SessionFactory sessionFactory;

@Bean
PersonService getPersonService() {
    return new PersonServiceImpl();
}

public List<User> getAll() {

    LOGGER.debug("Retrieving all users");
    Session session = sessionFactory.getCurrentSession();
    Query query = session.createQuery("from User ");
    return query.list();

}

public User get(Integer id) {

    Session session = sessionFactory.getCurrentSession();
    User user = (User) session.get(User.class, id);
    return user;

}

public void add(User user) {

    LOGGER.debug("Adding new user");
    Session session = sessionFactory.getCurrentSession();
    session.save(user);
}

public void delete(Integer id) {

    LOGGER.debug("Deleting existing user");
    Session session = sessionFactory.getCurrentSession();
    Query query = session.createQuery("from User where id = " + id);
    User user = (User) query.uniqueResult();
    List<Actions> actions = user.getActions();
    session.delete(user);
    for(Actions actionses: actions ){
        session.delete(actionses);
    }

}

public void edit(User user) {

    LOGGER.debug("Editing existing user");
    Session session = sessionFactory.getCurrentSession();
    User existingUser = (User) session.get(User.class, user.getId());
    existingUser.setLogin(user.getLogin());
    existingUser.setPassword(user.getPassword());
    existingUser.setReal_name(user.getReal_name());
    session.save(existingUser);
}
}

应用程序-上下文

<?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:context="http://www.springframework.org/schema/context"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
   xsi:schemaLocation="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/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

<!-- Activates various annotations to be detected in bean classes -->
<context:annotation-config />

<!-- Scans the classpath for annotated components that will be  
auto-registered as Spring beans.
 For example @Controller and @Service.-->

<context:component-scan base-package="com.oleg.project.*" />

<!-- Configures the annotation-driven Spring MVC Controller programming 
model.-->
<mvc:annotation-driven />

<!-- Load Hibernate related configuration -->
<import resource="hibernate-context.xml" />

</beans>

最后是我的StackTrace

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mainController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.oleg.project.Services.PersonServiceImpl com.oleg.project.Controller.MainController.personServiceImpl; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.oleg.project.Services.PersonServiceImpl] found for dependency: 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.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
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:305)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:834)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5016)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5528)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:652)
at org.apache.catalina.startup.HostConfig.manageApp(HostConfig.java:1809)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:301)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:618)
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:565)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:301)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1471)
at javax.management.remote.rmi.RMIConnectionImpl.access$300(RMIConnectionImpl.java:76)
at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1312)
at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1404)
at javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:832)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:323)
at sun.rmi.transport.Transport$1.run(Transport.java:200)
at sun.rmi.transport.Transport$1.run(Transport.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$79(TCPTransport.java:683)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
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)

原因:org.SpringFramework.Beans.Factory.BeanCreationException:无法自动连接字段:private Com.Oleg.Project.Services.PersonServiceImpl Com.Oleg.Project.Controller.MainController.PersonServiceImpl;嵌套异常为org.springframework.beans.factory.NoSuchBeanDefinitionException:未找到依赖项得[com.oleg.project.services.PersonServiceImpl]类型得合格bean:需要至少一个符合此依赖项自动候选条件得bean.依赖项批注:{@org.springframework.beans.factor.annotation.AutoWired(required=true)}(位于org.springframework.beans.factor.annotation.AutoWiredanNotationBeanPostProcessor.java:571)(位于org.springframework.beans.factor.annotation.InjectionMetadata.Injection(InjectionMetadata.88)(位于org.springframework.beans.factor.annotation.AutoWiredanNotationBeanPostProcessor.java:331))...58其他原因:org.springframework Work.Beans.Factory.NosuchBeanDefinitionException:找不到依赖项得[com.oleg.project.services.PersonServiceImpl]类型得合格bean:需要至少一个具有此依赖项自动候选资格得bean.依赖关系批注:{@org.springframework.beans.factory.annotation.AutoWired(required=true)}(位于org.springframework.beans.factory.support.defaultlistablebeanfactory.raisenosuchbeandefinitionexception(defaultlistablebeanfactory.java:1326)(位于org.springframework.beans.factory.support.defaultlistablebeanfactory.doResolveDependency(defaultlistablebeanfactory.1072)(位于java:967)在org.springframework.beans.factory.annotation.AutoWiredAnnotationBeanPostProcessor$AutoWiredFieldElement.Inject(AutoWiredAnnotationBeanPostProcessor.java:543)...60

共有1个答案

关冠宇
2023-03-14

您的服务定义如下。

@Service
@Transactional
public class ActionServiceImpl implements ActionService { ... }

现在发生的情况是由于配置中的 将创建ActionServiceImpl的实例。您还有一个 ,它检测@transactional并创建一个动态代理(一个不错的$Proxy12类或类似的东西)。该代理仅实现接口,因此是ActionService而不是ActionServiceImpl

为了应用AOP,spring使用代理,当涉及接口时,它默认使用JDK动态代理,这些代理仅是接口。

    null
  1. 在使用 时已经隐含了,您可以删除该行。
  2. base-package是它所表示的基本包它不使用表达式,请将com.oleg.project.*更改为om.oleg.project
  3. 服务中的@bean方法除了添加杂乱之外并没有添加任何东西,请删除它以清理代码。
 类似资料:
  • 被异常卡住,下面是日志: org.springframework.beans.factory.BeanCreation异常:创建名为扬声器的bean时出错:注入自动生成的依赖项失败;嵌套异常是org.springframework.beans.factory.BeanCreation异常:无法自动连接方法:公共最终无效org.mybatis.spring.support.SqlSessionDao

  • 这是我的当前设置:ProjectRepo: ProjectService: ProjectRestController:

  • 请帮我解决这个问题 错误日志: 控制器类: DAO类: 服务等级: Bean配置: 当spring试图创建< code > private UserService UserService时,它的自动连接似乎有问题; bean。作为参考,我检查了这些。 自动连线依赖项的注入失败; 上下文:组件扫描“未绑定 注入自动安装的依赖项失败,而试图访问道bean 这些并没有解决我的问题,因为我的代码中已经有这

  • 这是我的项目的结构: SCR/主/Java/COM/公司/配置 SCR/主/Java/COM/公司/控制器 SCR/Main/Java/COM/Company/MyProject SCR/主/Java/COM/公司/例外 在配置中,我有3个类:ProjectInitializer、ProjectConfiguration和ProjectContextListener。 ==============

  • 在试图通过浏览器访问我的应用程序时,我遇到了不少错误。错误包括: 无法自动连线方法:public void com。ProjectOne。Util。自定义HibernatedAOSupport。anyMethodName(org.hibernate.SessionFactory);嵌套的异常是org。springframework。豆。工厂NoSuchBeanDefinitionException

  • 问题内容: 我正在开发一个小型Java EE Hibernate Spring应用程序,出现错误: 这是我的控制器ArticleControleur,其中包含用于恢复文章列表的功能: 这是我的articleService: 这是我的应用程序上下文: 问题答案: 该错误表明不是注册的Bean。添加其中包含将在你的应用程序上下文中自动装配的bean的软件包: 或者,如果你想将所有子包包括在com.bd