严重:为 servlet [调度程序] org.springframework.beans.factory.NoSuchBeanDefinitionException 分配异常:

SEVERE: Allocate exception for servlet [dispatcher] org.springframework.beans.factory.NoSuchBeanDefinitionException:

我有expanda.js。我在我的 formcontroller.java 文件中调用此 dao,但出现以下错误。

我想我需要将 DAO 定义为一个 bean。我如何在 SpringWebConfig.java 文件中执行此操作?

我对spring没有太多控制权,抱歉

控制台错误:

SEVERE: Allocate exception for servlet [dispatcher] org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.esma.dao.ExpDao' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1777) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1333) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1287) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:130) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1415) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:608) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:531) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean[=15=](AbstractBeanFactory.java:335) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:944) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:925) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:588) at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:702) at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:578) at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:530) at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:170) at javax.servlet.GenericServlet.init(GenericServlet.java:158) at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1134) at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:777) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:135) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.base/java.lang.Thread.run(Thread.java:830)

ExpDao.java

package com.esma.dao;

import java.sql.ResultSet;    
import java.sql.SQLException;    
import java.util.List;    
import org.springframework.jdbc.core.BeanPropertyRowMapper;    
import org.springframework.jdbc.core.JdbcTemplate;    
import org.springframework.jdbc.core.RowMapper;

import com.esma.model.Expense;    
    
public class ExpDao {    
JdbcTemplate template;    
    
public void setTemplate(JdbcTemplate template) {    
    this.template = template;    
}    
public int save(Expense exp){    
    String sql="insert into Emp99(name,salary,designation) values('"+exp.getExpenseType()+"',"+exp.getQuantity()+","+exp.getPrice()+","+exp.getPaymentDate()+",'"+exp.getNote()+"' )";    
    return template.update(sql);    
}    
       
public List<Expense> getExpenses(){    
    return template.query("select * from expenses",new RowMapper<Expense>(){    
        public Expense mapRow(ResultSet result, int row) throws SQLException {    
            Expense e=new Expense();    
            e.setExpenseType(result.getString(2));    
            e.setQuantity(result.getInt(3));  
            e.setPrice(result.getInt(4));  
            e.setPaymentDate(result.getDate(5));    
            e.setNote(result.getString(6));    

            return e;    
        }    
    });    
}    
}   

SpringRootConfig.js


package com.esma.config;

import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;


@Configuration
@ComponentScan(basePackages ={"com.esma.dao"})
public class SpringRootConfig {
//TODO: Services, DAO, DataSource, Email Sender or some other business layer beans.
// In production the datasource configuration is done in properties file but for simplicity purpose it is hardcoded here.   
    @Bean
        public BasicDataSource getDataSource(){
            BasicDataSource ds = new BasicDataSource();
            ds.setDriverClassName("com.mysql.jdbc.Driver");
            ds.setUrl("jdbc:mysql://localhost:3306/apartmentmanagement");
            ds.setUsername("root");
            ds.setPassword("1234");
            ds.setMaxTotal(2);
            ds.setInitialSize(1);
            ds.setTestOnBorrow(true);
            ds.setValidationQuery("SELECT 1");
            ds.setDefaultAutoCommit(true);
            return ds;
        }
}


SpringWebConfig.js

/**
 * 
 */
package com.esma.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

import com.esma.dao.ExpDao;
import com.esma.model.Expense;

@Configuration
@ComponentScan(basePackages = { "com.esma" })
@EnableWebMvc
public class SpringWebConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // TODO Auto-generated method stub
        System.out.println("Inside Resource Handler");
        registry.addResourceHandler("/static/**").addResourceLocations("/static/");

    }

    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver vr = new InternalResourceViewResolver();
        vr.setViewClass(JstlView.class);
        vr.setPrefix("/WEB-INF/view/");
        vr.setSuffix(".jsp");
        return vr;
    }
    
    @Bean 
    public ExpDao expenceDao() {
        ExpDao exp = new ExpDao();
        exp.setTemplate(com.esma.dao.ExpDao.class);
        return exp;
    }
}

FormController.js

package com.esma.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.esma.dao.ExpDao;
import com.esma.model.Expense;

@Controller
public class FormController {

    @Autowired
    ExpDao dao;

    @RequestMapping(value = "/form", method = RequestMethod.GET)
    public String form() {
        new ModelAndView("expense", "expenseObject", new Expense());
        return "expenseForm";// JSP form view
    }

    @RequestMapping(value = "/expense/save", method = RequestMethod.POST)
    public String addExpense(@ModelAttribute("expenseObject") Expense expense, ModelMap model) {

        dao.save(expense);

        model.addAttribute("expenseType", expense.getExpenseType());
        model.addAttribute("quantity", expense.getQuantity());
        model.addAttribute("price", expense.getPrice());
        model.addAttribute("paymentDate", expense.getPaymentDate());
        model.addAttribute("note", expense.getNote());

        System.out.println(model.getAttribute("expenseType"));
        System.out.println(model.getAttribute("quantity"));
        System.out.println(model.getAttribute("price"));
        System.out.println(model.getAttribute("paymentDate"));
        System.out.println(model.getAttribute("note"));

        return "result";
    }

    @RequestMapping(value = "/list")
    public String expenseList(Model m) {
        List<Expense> list = dao.getExpenses();
        m.addAttribute("list", list);
        System.out.println("expense");
        return "expenseList";// JSP form view
    }
}

你好 Esma,欢迎来到 Whosebug。

由于您在 SpringWebConfig.js 中使用@Bean 批注明确声明了 ExpDao 类型的 bean,因此在 spring 上下文中注册的 bean 是 expenceDao,它与此代码部分中的方法名称相同:

 @Bean 
public ExpDao expenceDao() {
    ExpDao exp = new ExpDao();
    exp.setTemplate(com.esma.dao.ExpDao.class);
    return exp;
}

所以Spring容器将创建并注册一个ExpDao类型的bean,其名称(或id)为expenceDao(这是方法的名称expenceDao()

然后你要求 spring 使用这部分代码注入一个名为 expDao 的 bean,但没有找到。

    @Controller
    public class FormController {

     @Autowired
     ExpDao dao;
    // the rest of the code 
    }

所以 spring 将 return 一个 NoSuchBeanDefinitionException 因为它没有找到名称为 expDao 的 bean。

为了工作,您只需将 SpringWebConfig.java 文件中的方法名称 expenceDao() 更改为 expDao(),以便 spring 创建名称为 expDao 的 bean 和不是 expenceDao.

谢谢。