我关注this tutorial但毕竟我收到错误,我不明白为什么!!!
这是我的pom.xml
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>SpringExample</groupId>
<artifactId>SpringExample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<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>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.4.Final</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.3</version>
</dependency>
<dependency>
<groupId>org.jadira.usertype</groupId>
<artifactId>usertype.core</artifactId>
<version>5.0.0.GA</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceDirectory>src/main/webapp</warSourceDirectory>
<warName>SpringExample</warName>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
这是我的控制器
package org.dstech.examplespring.controller;
import java.util.List;
import java.util.Locale;
import javax.validation.Valid;
import org.dstech.examplespring.model.Employee;
import org.dstech.examplespring.service.EmployeeService;
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;
/**
* @author franksisca
*c
*/
@Controller
@RequestMapping("/")
public class AppController {
@Autowired
EmployeeService service;
@Autowired
MessageSource messageSource;
/*
* This method will list all existing employees.
*/
@RequestMapping(value = { "/", "/list" }, method = RequestMethod.GET)
public String listEmployees(ModelMap model) {
List<Employee> employees = service.findAllEmployees();
model.addAttribute("employees", employees);
return "allemployees";
}
/*
* This method will provide the medium to add a new employee.
*/
@RequestMapping(value = { "/new" }, method = RequestMethod.GET)
public String newEmployee(ModelMap model) {
Employee employee = new Employee();
model.addAttribute("employee", employee);
model.addAttribute("edit", false);
return "registration";
}
/*
* This method will be called on form submission, handling POST request for
* saving employee in database. It also validates the user input
*/
@RequestMapping(value = { "/new" }, method = RequestMethod.POST)
public String saveEmployee(@Valid Employee employee, BindingResult result,
ModelMap model) {
if (result.hasErrors()) {
return "registration";
}
/*
* Preferred way to achieve uniqueness of field [ssn] should be implementing custom @Unique annotation
* and applying it on field [ssn] of Model class [Employee].
*
* Below mentioned peace of code [if block] is to demonstrate that you can fill custom errors outside the validation
* framework as well while still using internationalized messages.
*
*/
if(!service.isEmployeeSsnUnique(employee.getId(), employee.getSsn())){
FieldError ssnError =new FieldError("employee","ssn",messageSource.getMessage("non.unique.ssn", new String[]{employee.getSsn()}, Locale.getDefault()));
result.addError(ssnError);
return "registration";
}
service.saveEmployee(employee);
model.addAttribute("success", "Employee " + employee.getName() + " registered successfully");
return "success";
}
/*
* This method will provide the medium to update an existing employee.
*/
@RequestMapping(value = { "/edit-{ssn}-employee" }, method = RequestMethod.GET)
public String editEmployee(@PathVariable String ssn, ModelMap model) {
Employee employee = service.findEmployeeBySsn(ssn);
model.addAttribute("employee", employee);
model.addAttribute("edit", true);
return "registration";
}
/*
* This method will be called on form submission, handling POST request for
* updating employee in database. It also validates the user input
*/
@RequestMapping(value = { "/edit-{ssn}-employee" }, method = RequestMethod.POST)
public String updateEmployee(@Valid Employee employee, BindingResult result,
ModelMap model, @PathVariable String ssn) {
if (result.hasErrors()) {
return "registration";
}
if(!service.isEmployeeSsnUnique(employee.getId(), employee.getSsn())){
FieldError ssnError =new FieldError("employee","ssn",messageSource.getMessage("non.unique.ssn", new String[]{employee.getSsn()}, Locale.getDefault()));
result.addError(ssnError);
return "registration";
}
service.updateEmployee(employee);
model.addAttribute("success", "Employee " + employee.getName() + " updated successfully");
return "success";
}
/*
* This method will delete an employee by it's SSN value.
*/
@RequestMapping(value = { "/delete-{ssn}-employee" }, method = RequestMethod.GET)
public String deleteEmployee(@PathVariable String ssn) {
service.deleteEmployeeBySsn(ssn);
return "redirect:/list";
}
}
这是应用程序初始化程序
package org.dstech.examplespring.configuration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
/**
* @author franksisca
*
*/
public class HelloWorldInit implements WebApplicationInitializer{
/* (non-Javadoc)
* @see org.springframework.web.WebApplicationInitializer#onStartup(javax.servlet.ServletContext)
*/
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(HelloWorldConfig.class);
context.setServletContext(servletContext);
ServletRegistration.Dynamic servlet =
servletContext.addServlet
("dispatcher", new DispatcherServlet(context));
servlet.setLoadOnStartup(1);
servlet.addMapping("/");
}
}
最后,但并非最不重要的是,当我启动tomcat时我的控制台错误
AVVERTENZA: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'appController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.dstech.exam
plespring.service.EmployeeService org.dstech.examplespring.controller.AppController.service; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type [org.dstech.examplespring.service.EmployeeService] 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)}
mag 18, 2016 6:09:29 PM org.springframework.web.servlet.DispatcherServlet initServletBean
GRAVE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'appController': Injection of autowired dependencies failed; nested exception is org.springfr
amework.beans.factory.BeanCreationException: Could not autowire field: org.dstech.examplespring.service.EmployeeService org.dstech.examplespring.controller.AppController.service; n
ested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.dstech.examplespring.service.EmployeeService] found for dependen
cy: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=tr
ue)}
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:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:666)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:538)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:492)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1090)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5231)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5518)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.dstech.examplespring.service.EmployeeService org.dstech.examplespring.controller.A
ppController.service; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.dstech.examplespring.service.EmployeeServ
ice] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotatio
n.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:573)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 26 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.dstech.examplespring.service.EmployeeService] found for dependency: expe
cted 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.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1373)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1119)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:545)
... 28 more
任何人都可以帮助我吗?我认为这是jade.time库的一个问题,但我不知道如何解决。如果我使用java.util.Date,我会得到同样的错误。
修改
抱歉,我忘记了我的服务
public interface EmployeeService {
Employee findById(int id);
void saveEmployee(Employee employee);
void updateEmployee(Employee employee);
void deleteEmployeeBySsn(String ssn);
List<Employee> findAllEmployees();
Employee findEmployeeBySsn(String ssn);
boolean isEmployeeSsnUnique(Integer id, String ssn);
}
这是我的实现
@Service("employeeService")
@Transactional
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
private EmployeeDao dao;
public Employee findById(int id) {
return dao.findById(id);
}
public void saveEmployee(Employee employee) {
dao.saveEmployee(employee);
}
/*
* Since the method is running with Transaction, No need to call hibernate update explicitly.
* Just fetch the entity from db and update it with proper values within transaction.
* It will be updated in db once transaction ends.
*/
public void updateEmployee(Employee employee) {
Employee entity = dao.findById(employee.getId());
if(entity!=null){
entity.setName(employee.getName());
entity.setJoiningDate(employee.getJoiningDate());
entity.setSalary(employee.getSalary());
entity.setSsn(employee.getSsn());
}
}
public void deleteEmployeeBySsn(String ssn) {
dao.deleteEmployee(ssn);
}
public List<Employee> findAllEmployees() {
return dao.findAllEmployees();
}
public Employee findEmployeeBySsn(String ssn) {
return dao.findEmployeeBySsn(ssn);
}
public boolean isEmployeeSsnUnique(Integer id, String ssn) {
Employee employee = findEmployeeBySsn(ssn);
return ( employee == null || ((id != null) && (employee.getId() == id)));
}
}
答案 0 :(得分:1)
从Stack跟踪中,它清楚地表明它无法找到EmployeeService。
No qualifying bean of type [org.dstech.examplespring.service.EmployeeService]
您正试图在失败的控制器中自动装配EmployeeService
@Autowired
EmployeeService service;
只需检查您是否在applicationContext中定义了此EmployeeService
bean,或者您已使用@Service