severe:为servlet[dispatcher]org.springframework.beans.factory.nosuchbeandefinitionexception分配异常:

g0czyy6m  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(409)

我有expanda.js。我在formcontroller.java文件中调用这个dao,但是我得到以下错误。
我想我需要把dao定义为一个bean。如何在springwebconfig.java文件中执行此操作?
对不起,我不能控制Spring
控制台错误:
严重:为servlet[dispatcher]org.springframework.beans.factory.nosuchbeandefinitionexception分配异常:没有类型为“com.esma.dao.expdao”的合格bean可用:至少需要1个符合autowire候选的bean。依赖项注解:{@org.springframework.beans.factory.annotation.autowired(required=true)}位于org.springframework.beans.factory.support.defaultlistablebeanfactory.raisenomatchingbeanfound(defaultlistablebeanfactory)。java:1777)在org.springframework.beans.factory.support.defaultlistablebeanfactory.doresolvedependency(defaultlistablebeanfactory)。java:1333)位于org.springframework.beans.factory.support.defaultlistablebeanfactory.resolvedependency(defaultlistablebeanfactory)。java:1287)在org.springframework.beans.factory.annotation.autowiredannotationbeanpostprocessor$autowiredFeldElement.inject(autowiredannotationbeanpostprocessor)。java:640)位于org.springframework.beans.factory.annotation.injectionmetadata.injector(injectionmetadata)。java:130)在org.springframework.beans.factory.annotation.autowiredannotationbeanpostprocessor.postprocessproperties(autowiredannotationbeanpostprocessor)。java:399)位于org.springframework.beans.factory.support.abstractautowirecapablebeanfactory.populatebean(abstractautowirecapablebeanfactory)。java:1415)在org.springframework.beans.factory.support.abstractautowirecapablebeanfactory.docreatebean(abstractautowirecapablebeanfactory)。java:608)位于org.springframework.beans.factory.support.abstractautowirecapablebeanfactory.createbean(abstractautowirecapablebeanfactory)。java:531)在org.springframework.beans.factory.support.abstractbeanfactory.lambda$dogetbean$0(abstractbeanfactory)。java:335)位于org.springframework.beans.factory.support.defaultsingletonbeanregistry.getsingleton(defaultsingletonbeanregistry)。java:234)位于org.springframework.beans.factory.support.abstractbeanfactory.dogetbean(abstractbeanfactory.com)。java:333)在org.springframework.beans.factory.support.abstractbeanfactory.getbean(abstractbeanfactory)。java:208)位于org.springframework.beans.factory.support.defaultlistablebeanfactory.PreInstanceSingletons(defaultlistablebeanfactory)。java:944)在org.springframework.context.support.abstractapplicationcontext.finishbeanfactoryinitialization(abstractapplicationcontext。java:925)在org.springframework.context.support.abstractapplicationcontext.refresh(abstractapplicationcontext。java:588)在org.springframework.web.servlet.frameworkservlet.configureandrefreshwebapplicationcontext(frameworkservlet)。java:702)位于org.springframework.web.servlet.frameworkservlet.initwebapplicationcontext(frameworkservlet。java:578)位于org.springframework.web.servlet.frameworkservlet.initservletbean(frameworkservlet。java:530)在org.springframework.web.servlet.httpservletbean.init(httpservletbean。java:170)在javax.servlet.genericservlet.init(genericservlet。java:158)位于org.apache.catalina.core.standardwrapper.initservlet(standardwrapper。java:1134)在org.apache.catalina.core.standardwrapper.allocate(standardwrapper。java:777)在org.apache.catalina.core.standardwrappervalve.invoke(standardwrappervalve。java:135)在org.apache.catalina.core.standardcontextvalve.invoke(standardcontextvalve。java:97)在org.apache.catalina.authenticator.authenticatorbase.invoke(authenticatorbase。java:541)在org.apache.catalina.core.standardhostvalve.invoke(standardhostvalve。java:143)在org.apache.catalina.valves.errorreportvalve.invoke(errorreportvalve。java:92)在org.apache.catalina.valves.abstractaccesslogvalve.invoke(abstractaccesslogvalve。java:690)在org.apache.catalina.core.standardenginevalve.invoke(standardenginevalve。java:78)在org.apache.catalina.connector.coyoteadapter.service(coyoteadapter。java:343)在org.apache.coyote.http11.http11processor.service(http11processor。java:374)在org.apache.coyote.abstractprocessorlight.process(abstractprocessorlight。java:65)在org.apache.coyote.abstractprotocol$connectionhandler.process(abstractprotocol。java:868)位于org.apache.tomcat.util.net.nioendpoint$socketprocessor.dorun(nioendpoint)。java:1590)在org.apache.tomcat.util.net.socketprocessorbase.run(socketprocessorbase。java:49)位于java.base/java.util.concurrent.threadpoolexecutor.runworker(threadpoolexecutor。java:1128)在java.base/java.util.concurrent.threadpoolexecutor$worker.run(threadpoolexecutor。java:628)在org.apache.tomcat.util.threads.taskthread$wrappingrunnable.run(任务线程。java:61)在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;
    }
}

窗体控制器.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
    }
}
pqwbnv8z

pqwbnv8z1#

你好,埃斯玛,欢迎来到stackoverflow。
由于您在springwebconfig.js中使用@bean annotation显式声明了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,但找不到这个bean。

@Controller
    public class FormController {

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

所以Spring会回来的 NoSuchBeanDefinitionException 因为它没有找到一个名为expdao的bean。
为了工作,您只需更改方法名 expenceDao()expDao() 在springwebconfig.java文件中,以便spring创建名为expdao而不是expncedao的bean。
谢谢。

相关问题