このプロジェクトで Bean を自動配線しようとしていますが、エラーが発生し続けます
この依存関係のオートワイヤー候補として適格な少なくとも 1 つの Bean が必要です。依存関係アノテーション: {@org.springframework.beans.factory.annotation.Autowired(required=true)"
ジャワ:
@Controller
@RequestMapping(value="/Home")
public class HomeController {
@Autowired
private Personrepo personRepo;
@RequestMapping(method=RequestMethod.GET)
public String showForm(ModelMap model){
List<Person> persons = personRepo.getAll();
model.addAttribute("persons", persons);
Person person = new Person();
model.addAttribute("person", person);
return "home";
}
@RequestMapping(value="/add", method=RequestMethod.POST)
public ModelAndView add(@ModelAttribute(value="person") Person person,BindingResult result){
ModelAndView mv = new ModelAndView("home");
if(!result.hasErrors()){
personRepo.add(person);
person = new Person();
mv.addObject("person", person);
}
mv.addObject("persons", personRepo.getAll());
return mv;
}
@RequestMapping(value="/edit", method=RequestMethod.POST)
public ModelAndView edit(@ModelAttribute(value="person") Person person,BindingResult result){
ModelAndView mv = new ModelAndView("home");
if(!result.hasErrors()){
personRepo.edit(person);
person = new Person();
mv.addObject("person", person);
}
mv.addObject("persons", personRepo.getAll());
return mv;
}
@RequestMapping(value="/delete", method=RequestMethod.POST)
public ModelAndView update(@ModelAttribute(value="person") Person person,BindingResult result){
ModelAndView mv = new ModelAndView("home");
if(!result.hasErrors()){
personRepo.delete(person.getId());
//personRepo.delete(person);
person = new Person();
mv.addObject("person", person);
}
mv.addObject("persons", personRepo.getAll());
return mv;
}
}
人
package com.app.domain;
import java.io.Serializable;
/**
* A simple POJO representing a Person
*/
public class Person implements Serializable {
private static final long serialVersionUID = -5527566248002296042L;
private String id;
private String firstName;
private String lastName;
private Double money;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
}
PersonRepo
package com.app.r;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.app.service.PersonService;
import com.app.domain.Person;
public interface Personrepo {
public void add(Person person);
public void edit(Person person);
public void delete(String id);
public List<Person> getAll();
}
個人サービス
package com.app.service;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import com.app.domain.Person;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Component
@Transactional
public class PersonService {
protected static Logger logger = Logger.getLogger("service");
private JdbcTemplate jdbcTemplate;
@Resource(name="dataSource")
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
/**
* Retrieves all persons
*
* @return a list of persons
*/
public List<Person> getAll() {
logger.debug("Retrieving all persons");
// Prepare our SQL statement
String sql = "select id, first_name, last_name, money from person";
// Maps a SQL result to a Java object
RowMapper<Person> mapper = new RowMapper<Person>() {
public Person mapRow(ResultSet rs, int rowNum) throws SQLException {
Person person = new Person();
person.setId(rs.getString("id"));
person.setFirstName(rs.getString("first_name"));
person.setLastName(rs.getString("last_name"));
person.setMoney(rs.getDouble("money"));
return person;
}
};
// Retrieve all
return jdbcTemplate.query(sql, mapper);
}
/**
* Adds a new person
*
* @param firstName the first name of the person
* @param lastName the last name of the person
* @param money the money of the person
*/
public void add(String firstName, String lastName, Double money) {
logger.debug("Adding new person");
// Prepare our SQL statement using Named Parameters style
String sql = "insert into person(first_name, last_name, money) values " +
"(:firstName, :lastName, :money)";
// Assign values to parameters
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("firstName", firstName);
parameters.put("lastName", lastName);
parameters.put("money", money);
// Save
jdbcTemplate.update(sql, parameters);
}
/**
* Deletes an existing person
* @param id the id of the existing person
*/
public void delete(String id) {
logger.debug("Deleting existing person");
// Prepare our SQL statement using Unnamed Parameters style
String sql = "delete from person where id = ?";
// Assign values to parameters
Object[] parameters = new Object[] {id};
// Delete
jdbcTemplate.update(sql, parameters);
}
/**
* Edits an existing person
* @param id the id of the existing person
* @param firstName the first name of the existing person
* @param lastName the last name of the existing person
* @param money the money of the existing person
*/
public void edit(String id, String firstName, String lastName, Double money) {
logger.debug("Editing existing person");
// Prepare our SQL statement
String sql = "update person set first_name = :firstName, " +
"last_name = :lastName, money = :money where id = :id";
// Assign values to parameters
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("id", id);
parameters.put("firstName", firstName);
parameters.put("lastName", lastName);
parameters.put("money", money);
// Edit
jdbcTemplate.update(sql, parameters);
}
}
サーブレット-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />
<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB- INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<!-- Activates various annotations to be detected in bean classes -->
<context:annotation-config />
<!-- Scans the classpath for annotated components that will be auto-registered as Spring beans.
For example @Controller and @Service. Make sure to set the correct base-package-->
</beans:beans>
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web- app_2_5.xsd">
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<!-- Processes application requests -->
<servlet>
<servlet-name>servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
org.springframework.web.context.ContextLoaderListener
<servlet-mapping>
<servlet-name>servlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
エラーコンソール
INFO : org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'servlet': initialization started
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Refreshing WebApplicationContext for namespace 'servlet-servlet': startup date [Wed May 08 15:59:09 BST 2013]; root of context hierarchy
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/servlet-context.xml]
INFO : org.springframework.context.annotation.ClassPathBeanDefinitionScanner - JSR-330 'javax.inject.Named' annotation found and supported for component scanning
INFO : org.springframework.context.annotation.ClassPathBeanDefinitionScanner - JSR-330 'javax.inject.Named' annotation found and supported for component scanning
INFO : org.springframework.context.annotation.ClassPathBeanDefinitionScanner - JSR-330 'javax.inject.Named' annotation found and supported for component scanning
INFO : org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@426b51d8: defining beans [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#0,org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver#0,org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver#0,org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,org.springframework.web.servlet.view.InternalResourceViewResolver#0,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,homeController,personService,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/Home/add],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.ModelAndView com.app.a.HomeController.add(com.app.domain.Person,org.springframework.validation.BindingResult)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/Home/delete],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.ModelAndView com.app.a.HomeController.update(com.app.domain.Person,org.springframework.validation.BindingResult)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/Home],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String com.app.a.HomeController.showForm(org.springframework.ui.ModelMap)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/Home/edit],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.ModelAndView com.app.a.HomeController.edit(com.app.domain.Person,org.springframework.validation.BindingResult)
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@426b51d8: defining beans [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#0,org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver#0,org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver#0,org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,org.springframework.web.servlet.view.InternalResourceViewResolver#0,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,homeController,personService,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy
ERROR: org.springframework.web.servlet.DispatcherServlet - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'homeController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.app.r.Personrepo com.app.a.HomeController.personRepo; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.app.r.Personrepo] 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)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:631)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:588)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:645)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:508)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:449)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:133)
at javax.servlet.GenericServlet.init(GenericServlet.java:160)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1266)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1185)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1080)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5027)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5314)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.app.r.Personrepo com.app.a.HomeController.personRepo; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.app.r.Personrepo] 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)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:506)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
... 30 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.app.r.Personrepo] 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)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:924)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:793)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:707)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)
... 32 more
May 8, 2013 3:59:10 PM org.apache.catalina.core.ApplicationContext log
SEVERE: StandardWrapper.Throwable
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'homeController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.app.r.Personrepo com.app.a.HomeController.personRepo; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.app.r.Personrepo] 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)}
実装による PersonService クラスの更新
package com.app.service;
@Component
public class PersonService implements Personrepo {
protected static Logger logger = Logger.getLogger("service");
private JdbcTemplate jdbcTemplate;
@Resource(name="dataSource")
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
/**
* Retrieves all persons
*
* @return a list of persons
*/
public List<Person> getAll() {
logger.debug("Retrieving all persons");
// Prepare our SQL statement
String sql = "select id, first_name, last_name, money from person";
// Maps a SQL result to a Java object
RowMapper<Person> mapper = new RowMapper<Person>() {
public Person mapRow(ResultSet rs, int rowNum) throws SQLException {
Person person = new Person();
person.setId(rs.getString("id"));
person.setFirstName(rs.getString("first_name"));
person.setLastName(rs.getString("last_name"));
person.setMoney(rs.getDouble("money"));
return person;
}
};
// Retrieve all
return jdbcTemplate.query(sql, mapper);
}
/**
* Adds a new person
*
* @param firstName the first name of the person
* @param lastName the last name of the person
* @param money the money of the person
*/
public void add(String firstName, String lastName, Double money) {
logger.debug("Adding new person");
// Prepare our SQL statement using Named Parameters style
String sql = "insert into person(first_name, last_name, money) values " +
"(:firstName, :lastName, :money)";
// Assign values to parameters
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("firstName", firstName);
parameters.put("lastName", lastName);
parameters.put("money", money);
// Save
jdbcTemplate.update(sql, parameters);
}
/**
* Deletes an existing person
* @param id the id of the existing person
*/
public void delete(String id) {
logger.debug("Deleting existing person");
// Prepare our SQL statement using Unnamed Parameters style
String sql = "delete from person where id = ?";
// Assign values to parameters
Object[] parameters = new Object[] {id};
// Delete
jdbcTemplate.update(sql, parameters);
}
/**
* Edits an existing person
* @param id the id of the existing person
* @param firstName the first name of the existing person
* @param lastName the last name of the existing person
* @param money the money of the existing person
*/
public void edit(String id, String firstName, String lastName, Double money) {
logger.debug("Editing existing person");
// Prepare our SQL statement
String sql = "update person set first_name = :firstName, " +
"last_name = :lastName, money = :money where id = :id";
// Assign values to parameters
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("id", id);
parameters.put("firstName", firstName);
parameters.put("lastName", lastName);
parameters.put("money", money);
// Edit
jdbcTemplate.update(sql, parameters);
}
@Override
public void add(Person person) {
// TODO Auto-generated method stub
}
@Override
public void edit(Person person) {
// TODO Auto-generated method stub
}
}
これを追加しました
Appilcation context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- Activates various annotations to be detected in bean classes -->
<context:annotation-config />
<!-- Scans the classpath for annotated components that will be auto-registered as Spring beans.
For example @Controller and @Service. Make sure to set the correct base-package-->
<context:component-scan base-package="com.app.a" />
<!-- Configures the annotation-driven Spring MVC Controller programming model.
Note that, with Spring 3.0, this tag works in Servlet MVC only! -->
<mvc:annotation-driven />
<import resource="jdbc-context.xml" />
現在、データソース Bean エラーは発生していませんが、autowire Bean が見つからないというエラーのみが発生しています。com.app.service.PersonService com.app.r.Personrepo. アプリケーション context.xml で
http not found エラー uri が表示されます