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

严重:为servlet[dispatcher]组织分配异常。springframework。豆。工厂NoSuchBean定义异常:

茅桐
2023-03-14

我有扩张器。js。我在formcontroller中调用此刀。java文件,但我得到以下错误。

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

对不起,我对Spring没有太多的控制

控制台错误:

严重:为servlet[dispatcher]组织分配异常。springframework。豆。工厂NoSuchBeanDefinitionException:没有类型为“com”的合格bean。埃斯马。刀。ExpDao'可用:至少需要1个符合autowire候选条件的bean。依赖项注释:{@org.springframework.beans.factory.annotation.Autowired(required=true)}。springframework。豆。工厂支持DefaultListableBeanFactory。raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1777)位于org。springframework。豆。工厂支持DefaultListableBeanFactory。doResolveDependency(DefaultListableBeanFactory.java:1333)位于org。springframework。豆。工厂支持DefaultListableBeanFactory。org上的resolveDependency(DefaultListableBeanFactory.java:1287)。springframework。豆。工厂注释。AutoWiredNotationBeanPostProcessor$AutoWiredFeldElement。在org上注入(autowirednotationbeanpostprocessor.java:640)。springframework。豆。工厂注释。注入元数据。在org上注入(InjectionMetadata.java:130)。springframework。豆。工厂注释。AutowiredNotationBeanPostProcessor。org上的后处理属性(AutowiredNotationBeanPostProcessor.java:399)。springframework。豆。工厂支持AbstractAutowireCapableBeanFactory。org上的populateBean(AbstractAutowireCapableBeanFactory.java:1415)。springframework。豆。工厂支持AbstractAutowireCapableBeanFactory。org上的doCreateBean(AbstractAutowireCapableBeanFactory.java:608)。springframework。豆。工厂支持AbstractAutowireCapableBeanFactory。在org上创建Bean(AbstractAutowireCapableBeanFactory.java:531)。springframework。豆。工厂支持抽象工厂。org上的lambda$doGetBean$0(AbstractBeanFactory.java:335)。springframework。豆。工厂支持DefaultSingletonBeanRegistry。org上的getSingleton(DefaultSingletonBeanRegistry.java:234)。springframework。豆。工厂支持抽象工厂。org上的doGetBean(AbstractBeanFactory.java:333)。springframework。豆。工厂支持抽象工厂。org上的getBean(AbstractBeanFactory.java:208)。springframework。豆。工厂支持DefaultListableBeanFactory。在org上预实例化Singleton(DefaultListableBeanFactory.java:944)。springframework。上下文支持AbstractApplicationContext。在org上完成BeanFactoryInitialization(AbstractApplicationContext.java:925)。springframework。上下文支持AbstractApplicationContext。在org上刷新(AbstractApplicationContext.java:588)。springframework。网状物servlet。FrameworkServlet。在org上配置和刷新WebApplicationContext(FrameworkServlet.java:702)。springframework。网状物servlet。FrameworkServlet。位于org的initWebApplicationContext(FrameworkServlet.java:578)。springframework。网状物servlet。FrameworkServlet。位于org的initServletBean(FrameworkServlet.java:530)。springframework。网状物servlet。HttpServletBean。javax上的init(HttpServletBean.java:170)。servlet。GenericServlet。org上的init(GenericServlet.java:158)。阿帕奇。卡塔琳娜。果心标准包装。org上的initServlet(StandardWrapper.java:1134)。阿帕奇。卡塔琳娜。果心标准包装。在组织中分配(StandardWrapper.java:777)。阿帕奇。卡塔琳娜。果心标准包装阀。在org上调用(StandardWrapperValve.java:135)。阿帕奇。卡塔琳娜。果心标准连接阀。在org上调用(StandardContextValve.java:97)。阿帕奇。卡塔琳娜。验证者。AuthenticatorBase。在org调用(AuthenticatorBase.java:541)。阿帕奇。卡塔琳娜。果心标准阀门。在org上调用(StandardHostValve.java:143)。阿帕奇。卡塔琳娜。阀门。错误报告阀。在org调用(ErrorReportValve.java:92)。阿帕奇。卡塔琳娜。阀门。抽象逻辑阀。在org调用(AbstractAccessLogValve.java:690)。阿帕奇。卡塔琳娜。果心标准引擎版本。在org上调用(StandardEngineValve.java:78)。阿帕奇。卡塔琳娜。连接器。郊狼适应者。服务(CoyoteAdapter.java:343)位于org。阿帕奇。郊狼。http11。http11处理器。位于org的服务(Http11Processor.java:374)。阿帕奇。郊狼。抽象光。org上的进程(AbstractProcessorLight.java:65)。阿帕奇。郊狼。AbstractProtocol$ConnectionHandler。进程(AbstractProtocol.java:868)位于org。阿帕奇。公猫util。网NioEndpoint$SocketProcessor。doRun(NioEndpoint.java:1590)位于org。阿帕奇。公猫util。网SocketProcessorBase。在java上运行(SocketProcessorBase.java:49)。base/java。util。同时发生的线程池执行器。java上的runWorker(ThreadPoolExecutor.java:1128)。base/java。util。同时发生的线程池执行器$Worker。在org上运行(ThreadPoolExecutor.java:628)。阿帕奇。公猫util。线程。TaskThread$WrappingRunnable。在java上运行(TaskThread.java:61)。base/java。朗。丝线。运行(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
    }
}

共有1个答案

浦德义
2023-03-14

你好,埃斯玛,欢迎来到stackoverflow。

因为您在SpringWebConfig中使用@bean注释明确声明了ExpDao类型的bean。js,在spring上下文中注册的bean是expenceDao,它与此代码段中的方法名相同:

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

因此,Spring容器将创建并注册一个名为(或id)exence道的类型的bean(这是方法的名称exence道()

然后,您要求Spring使用这段代码注入一个没有找到的名为expDao的bean。

    @Controller
    public class FormController {

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

因此spring将返回一个NoSuchBeanDefinitionException,因为它没有找到名为expDao的bean。

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

谢谢。

 类似资料: