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

未满足的依赖项异常:创建名为的bean时出错

贺桐
2023-03-14

“我是Spring新手,我刚开始一个Spring MVC CRUD项目,但在尝试了很多方法之后,我一次又一次地面临同样的错误。

这是打印HTTP状态500的第一个异常-内部服务器错误。

HTTP状态500–内部服务器错误

javax。servlet。ServletException:Servlet。servlet[dispatcher]的init()引发异常组织。阿帕奇。卡塔琳娜。验证者。AuthenticatorBase。调用(AuthenticatorBase.java:540)org。阿帕奇。卡塔琳娜。阀门。打开阀门。调用(ErrorReportValve.java:92)org。阿帕奇。卡塔琳娜。阀门。抽象逻辑阀。调用(AbstractAccessLogValve.java:687)org。阿帕奇。卡塔琳娜。连接器。郊狼适应者。服务(CoyoteAdapter.java:357)org。阿帕奇。郊狼。http11。HTTP11处理器。服务(Http11Processor.java:382)组织。阿帕奇。郊狼。抽象过程光。process(AbstractProcessorLight.java:65)org。阿帕奇。郊狼。AbstractProtocol$ConnectionHandler。过程(AbstractProtocol.java:895)组织。阿帕奇。公猫util。网NioEndpoint$SocketProcessor。doRun(NioEndpoint.java:1732)org。阿帕奇。公猫util。网SocketProcessorBase。运行(SocketProcessorBase.java:49)org。阿帕奇。公猫util。线程。线程池执行器。runWorker(ThreadPoolExecutor.java:1191)org。阿帕奇。公猫util。线程。ThreadPoolExecutor$Worker。运行(ThreadPoolExecutor.java:659)org。阿帕奇。公猫util。线程。TaskThread$wrappingranable。运行(TaskThread.java:61)java。朗。丝线。运行(未知源)

未满足的依赖项异常

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'studentDao' defined in file [C:\Users\MOHIT SINGH\Documents\workspace-spring-tool-suite-4-4.6.2.RELEASE\.metadata\.plugins\org.eclipse.wst.server.core\tmp2\wtpwebapps\STUDENT-SPRING-MVC\WEB-INF\classes\com\spring\student\dao\StudentDaoImpl.class]: Unsatisfied dependency expressed through constructor parameter 0: No qualifying bean of type [java.lang.Class] found for dependency [java.lang.Class<com.spring.student.model.Student>]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.Class] found for dependency [java.lang.Class<com.spring.student.model.Student>]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
    org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
    org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:189)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1143)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1046)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:775)
    org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
    org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
    org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668)
    org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:540)
    org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494)
    org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    javax.servlet.GenericServlet.init(GenericServlet.java:158)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:687)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
    org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)
    org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895)
    org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1732)
    org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
    org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    java.lang.Thread.run(Unknown Source)

NoSuchBeanDefinitionException

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.Class] found for dependency [java.lang.Class<com.spring.student.model.Student>]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
    org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1398)
    org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1051)
    org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1018)
    org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:834)
    org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
    org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:189)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1143)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1046)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:775)
    org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
    org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
    org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668)
    org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:540)
    org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494)
    org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    javax.servlet.GenericServlet.init(GenericServlet.java:158)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:687)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
    org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)
    org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895)
    org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1732)
    org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
    org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    java.lang.Thread.run(Unknown Source)

密码

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.java.spring</groupId>
    <artifactId>STUDENT-SPRING-MVC</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>STUDENT-SPRING-MVC Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
        <springframework.version>4.3.0.RELEASE</springframework.version>
        <hibernate.version>4.3.6.Final</hibernate.version>
        <mysql.version>5.1.31</mysql.version>
        <joda-time.version>2.3</joda-time.version>
    </properties>
    <dependencies>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${springframework.version}</version>
        </dependency>

        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        <!-- jsr303 validation -->
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.1.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.1.3.Final</version>
        </dependency>

        <!-- MySQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.26</version>
        </dependency>

        <!-- Joda-Time -->
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>${joda-time.version}</version>
        </dependency>

        <!-- To map JodaTime with database type -->
        <dependency>
            <groupId>org.jadira.usertype</groupId>
            <artifactId>usertype.core</artifactId>
            <version>3.0.0.CR1</version>
        </dependency>

        <!-- Servlet+JSP+JSTL -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>


        <!-- Testing dependencies -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${springframework.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>7.5</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>STUDENT-SPRING-MVC</finalName>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.6</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

配置

package com.spring.student.configuration;

import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@Configuration
@EnableWebMvc
@ComponentScan("com.spring.student")
public class MyWebConfig {

    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");

        return viewResolver;
    }

    @Bean
    public MessageSource messageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasename("messages");
        return messageSource;
    }
}

Servletilizer

package com.spring.student.configuration;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class ServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {

        return null;
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {

        return new Class[] {MyWebConfig.class};
    }

    @Override
    protected String[] getServletMappings() {

        return new String[] { "/" };
    }

}

冬眠形态

package com.spring.student.configuration;

import java.util.Properties;

import javax.sql.DataSource;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@ComponentScan({ "com.spring.student.configuration" })
@PropertySource(value = { "classpath:application.properties" })
public class MyHibernateConfig {

    @Autowired
    private Environment environment;

    @Bean
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(new String[] { "com.spring.student.model" });
        sessionFactory.setHibernateProperties(hibernateProperties());
        return sessionFactory;
    }

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
        dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
        dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
        dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
        return dataSource;
    }

    public Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
        properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show.sql"));
        properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
        return properties;
    }

    @Bean
    @Autowired
    public HibernateTransactionManager transactionManager(SessionFactory s) {
        HibernateTransactionManager txManager = new HibernateTransactionManager();
        txManager.setSessionFactory(s);
        return txManager;
    }
}

package com.spring.student.dao;

import java.io.Serializable;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import java.lang.reflect.ParameterizedType;
import org.springframework.beans.factory.annotation.Autowired;

public abstract class AbstStudentDao<PK extends Serializable, T> {

    private final Class<T> persistentClass;

    @SuppressWarnings("unchecked")
    public AbstStudentDao(Class<T> persistentClass) {
        super();
        this.persistentClass = (Class) ((ParameterizedType) this.getClass().getGenericSuperclass())
                .getActualTypeArguments()[1];
    }

    @Autowired
    private SessionFactory sessionFactory;

    protected Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    @SuppressWarnings("unchecked")
    public T getByKey(PK key) {
        return (T) getSession().get(persistentClass, key);
    }

    public void persist(T entity) {
        getSession().persist(entity);
    }

    public void saveOrUpdate(T entity) {
        getSession().saveOrUpdate(entity);
    }

    public void delete(T entity) {
        getSession().delete(entity);
    }

    protected Criteria createEntityCriteria() {
        return getSession().createCriteria(persistentClass);
    }
}

道明


package com.spring.student.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.spring.student.model.Student;

@Repository("studentDao")
public class StudentDaoImpl extends AbstStudentDao<Integer, Student> implements StudentDao {

    public StudentDaoImpl(Class<Student> persistentClass) {
        super(persistentClass);

    }
    
    public void saveOrUpdate(Student student) {
        super.saveOrUpdate(student);
    }

    @Override
    public Student findById(int id) {

        return getByKey(id);
    }

    @Override
    public void saveStudent(Student student) {
        persist(student);

    }

    @Override
    public void deleteStudentByCode(String code) {
        Query query = getSession().createQuery("delete from student where code = :code");
        query.setParameter("code", code);
        query.executeUpdate();

    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Student> findAllStudents() {
        Criteria criteria = createEntityCriteria();
        return (List<Student>) criteria.list();

    }

    @Override
    public Student findStudentByCode(String code) {

        Criteria criteria = createEntityCriteria();
        criteria.add(Restrictions.eq("code", code));
        return (Student) criteria.uniqueResult();
    }

}

服务信息


package com.spring.student.service;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.spring.student.dao.StudentDao;
import com.spring.student.model.Student;

@Service("studentService")
@Transactional
public class StudentServiceImpl implements StudentService {

    private StudentDao studentDao;

    @Override
    public Student findById(int Id) {

        return studentDao.findById(Id);
    }

    @Override
    public void saveStudent(Student student) {

        studentDao.saveStudent(student);

    }

    @Override
    public void updateStudent(Student student) {

        Student entity = studentDao.findById(student.getId());
        if (entity != null) {
            entity.setName(student.getName());
            entity.setEnteringDate(student.getEnteringDate());
            entity.setNationality(student.getNationality());
            entity.setCode(student.getCode());
        }

    }

    @Override
    public List<Student> findAllStudent() {

        return studentDao.findAllStudents();
    }

    @Override
    public Student findStudentByCode(String code) {

        return studentDao.findStudentByCode(code);
    }

    @Override
    public boolean isStudentCodeUnique(Integer id, String code) {
        Student student = findStudentByCode(code);
        return (student == null || ((id != null) && (student.getId() == id)));
    }

    @Override
    public void deleteStudentByCode(String code) {
        studentDao.deleteStudentByCode(code);

    }

}

控制器


package com.spring.student.controller;

import java.util.Locale;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.spring.student.model.Student;
import com.spring.student.service.StudentService;

@Controller
@RequestMapping("/")
public class MyController {

    @Autowired
    StudentService service;

    @Autowired
    MessageSource messageSource;

    @RequestMapping(value = { "/new" }, method = RequestMethod.GET)
    public String studentList(ModelMap model) {

        Student student = new Student();
        model.addAttribute("student", student);
        model.addAttribute("edit", false);
        return "registration";
    }

    @RequestMapping(value = { "/new" }, method = RequestMethod.POST)
    public String saveStudent(@Valid Student student, BindingResult result, ModelMap model) {
        if (result.hasErrors()) {
            return "registration";
        }
        if (!service.isStudentCodeUnique(student.getId(), student.getCode())) {
            FieldError codeError = new FieldError("student", "code", messageSource.getMessage("non.unique.code",
                    new String[] { student.getCode() }, Locale.getDefault()));
            result.addError(codeError);
            return "registration";
        }
        service.saveStudent(student);
        model.addAttribute("success", "student" + student.getName() + "Registration Successfull");
        return "success";
    }

    @RequestMapping(value = { "/edit-{code}-student" }, method = RequestMethod.GET)
    public String editStudent(@PathVariable String code, ModelMap model) {
        Student student = service.findStudentByCode(code);
        model.addAttribute("student", student);
        model.addAttribute("edit", true);
        return "registration";
    }

    @RequestMapping(value = { "/edit-{code}-student" }, method = RequestMethod.POST)
    public String updateStudent(@Valid Student student, BindingResult result, ModelMap model,
            @PathVariable String code) {
        if (result.hasErrors()) {
            return "registration";
        }

        if (!service.isStudentCodeUnique(student.getId(), student.getCode())) {
            FieldError codeError = new FieldError("student", "code", messageSource.getMessage("non.unique.code",
                    new String[] { student.getCode() }, Locale.getDefault()));
            result.addError(codeError);
            return "registration";
        }
        service.saveStudent(student);
        model.addAttribute("success", "student" + student.getName() + "Update SuccessFully Completed");
        return "success";
    }

    @RequestMapping(value = { "/delete-{code}-student" }, method = RequestMethod.GET)
    public String deleteStudent(@PathVariable String code) {
        service.deleteStudentByCode(code);
        return "redirect:/list";
    }
}

共有3个答案

颜云瀚
2023-03-14

首先,您应该自动生成StrudentDoa其次,您不需要在括号@Service()中定义服务名称

package com.spring.student.service;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.spring.student.dao.StudentDao;
import com.spring.student.model.Student;

@Service
@Transactional
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentDao studentDao;

    @Override
    public Student findById(int Id) {

        return studentDao.findById(Id);
    }

    @Override
    public void saveStudent(Student student) {

        studentDao.saveStudent(student);

    }

    @Override
    public void updateStudent(Student student) {

        Student entity = studentDao.findById(student.getId());
        if (entity != null) {
            entity.setName(student.getName());
            entity.setEnteringDate(student.getEnteringDate());
            entity.setNationality(student.getNationality());
            entity.setCode(student.getCode());
        }

    }

    @Override
    public List<Student> findAllStudent() {

        return studentDao.findAllStudents();
    }

    @Override
    public Student findStudentByCode(String code) {

        return studentDao.findStudentByCode(code);
    }

    @Override
    public boolean isStudentCodeUnique(Integer id, String code) {
        Student student = findStudentByCode(code);
        return (student == null || ((id != null) && (student.getId() == id)));
    }

    @Override
    public void deleteStudentByCode(String code) {
        studentDao.deleteStudentByCode(code);

    }

}
别宏盛
2023-03-14

StudentDaoImpl类的构造函数更改为

public StudentDaoImpl() {
            super(Student.class);
   }

StudentServiceImplclass中使用autowirestudentdao

希望它能奏效

穆丁雨
2023-03-14

你有没有试过

 类似资料: