2015-12-03 2 views
-1

Я использую этот tutorial для примера Spring MVC, но я использую PostgreSQL.org.springframework.web.servlet.DispatcherServlet.initServletBean Ошибка инициализации контекста

И у меня есть много исключений, я искал, но ничего не помогло.

Это исключение:

SEVERE [RMI TCP Connection(3)-127.0.0.1] org.springframework.web.servlet.DispatcherServlet.initServletBean 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 net.codejava.spring.dao.ContactDAO net.codejava.spring.controller.HomeController.contactDAO; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getContactDAO' defined in class path resource [net/codejava/spring/config/MvcConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public net.codejava.spring.dao.ContactDAO net.codejava.spring.config.MvcConfiguration.getContactDAO()] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getDataSource' defined in class path resource [net/codejava/spring/config/MvcConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource net.codejava.spring.config.MvcConfiguration.getDataSource()] threw exception; nested exception is java.lang.IllegalStateException: Could not load JDBC driver class [org.postgresql.Driver] 

Если я понимаю, право у меня есть проблема с нагрузкой JDBC Driver, но я уже добавил это в pom.xml

Мой исходный код:

MvcConfiguration:

package net.codejava.spring.config; 

import javax.sql.DataSource; 

import net.codejava.spring.dao.ContactDAO; 
import net.codejava.spring.dao.ContactDAOImpl; 

import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.ComponentScan; 
import org.springframework.context.annotation.Configuration; 
import org.springframework.jdbc.datasource.DriverManagerDataSource; 
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.WebMvcConfigurerAdapter; 
import org.springframework.web.servlet.view.InternalResourceViewResolver; 

@Configuration 
@ComponentScan(basePackages="net.codejava.spring") 
@EnableWebMvc 
public class MvcConfiguration extends WebMvcConfigurerAdapter{ 

    @Bean 
    public ViewResolver getViewResolver(){ 
     InternalResourceViewResolver resolver = new InternalResourceViewResolver(); 
     resolver.setPrefix("/WEB-INF/views/"); 
     resolver.setSuffix(".jsp"); 
     return resolver; 
    } 

    @Override 
    public void addResourceHandlers(ResourceHandlerRegistry registry) { 
     registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); 
    } 

    @Bean 
    public DataSource getDataSource() { 
     DriverManagerDataSource dataSource = new DriverManagerDataSource(); 
     dataSource.setDriverClassName("org.postgresql.Driver"); 
     dataSource.setUrl("jdbc:postgresql://localhost:5432/contactdb"); 
     dataSource.setUsername("postgres"); 
     dataSource.setPassword("3517571"); 

     return dataSource; 
    } 

    @Bean 
    public ContactDAO getContactDAO() { 
     return new ContactDAOImpl(getDataSource()); 
    } 
} 

HomeController:

package net.codejava.spring.controller; 

import java.io.IOException; 
import java.util.List; 

import javax.servlet.http.HttpServletRequest; 

import net.codejava.spring.dao.ContactDAO; 
import net.codejava.spring.model.Contact; 

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Controller; 
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; 

/** 
* This controller routes accesses to the application to the appropriate 
* hanlder methods. 
* @author www.codejava.net 
* 
*/ 
@Controller 
public class HomeController { 

    @Autowired 
    private ContactDAO contactDAO; 

    @RequestMapping(value="/") 
    public ModelAndView listContact(ModelAndView model) throws IOException{ 
     List<Contact> listContact = contactDAO.list(); 
     model.addObject("listContact", listContact); 
     model.setViewName("home"); 

     return model; 
    } 

    @RequestMapping(value = "/newContact", method = RequestMethod.GET) 
    public ModelAndView newContact(ModelAndView model) { 
     Contact newContact = new Contact(); 
     model.addObject("contact", newContact); 
     model.setViewName("ContactForm"); 
     return model; 
    } 

    @RequestMapping(value = "/saveContact", method = RequestMethod.POST) 
    public ModelAndView saveContact(@ModelAttribute Contact contact) { 
     contactDAO.saveOrUpdate(contact);  
     return new ModelAndView("redirect:/"); 
    } 

    @RequestMapping(value = "/deleteContact", method = RequestMethod.GET) 
    public ModelAndView deleteContact(HttpServletRequest request) { 
     int contactId = Integer.parseInt(request.getParameter("id")); 
     contactDAO.delete(contactId); 
     return new ModelAndView("redirect:/"); 
    } 

    @RequestMapping(value = "/editContact", method = RequestMethod.GET) 
    public ModelAndView editContact(HttpServletRequest request) { 
     int contactId = Integer.parseInt(request.getParameter("id")); 
     Contact contact = contactDAO.get(contactId); 
     ModelAndView model = new ModelAndView("ContactForm"); 
     model.addObject("contact", contact); 

     return model; 
    } 
} 

ContactDAO:

package net.codejava.spring.dao; 

import java.util.List; 

import net.codejava.spring.model.Contact; 

/** 
* Defines DAO operations for the contact model. 
* @author www.codejava.net 
* 
*/ 
public interface ContactDAO { 

    public void saveOrUpdate(Contact contact); 

    public void delete(int contactId); 

    public Contact get(int contactId); 

    public List<Contact> list(); 
} 

ContactDAOImpl:

package net.codejava.spring.dao; 

import java.sql.ResultSet; 
import java.sql.SQLException; 
import java.util.List; 

import javax.sql.DataSource; 

import net.codejava.spring.model.Contact; 

import org.springframework.dao.DataAccessException; 
import org.springframework.jdbc.core.JdbcTemplate; 
import org.springframework.jdbc.core.ResultSetExtractor; 
import org.springframework.jdbc.core.RowMapper; 

/** 
* An implementation of the ContactDAO interface. 
* @author www.codejava.net 
* 
*/ 

public class ContactDAOImpl implements ContactDAO { 

    private JdbcTemplate jdbcTemplate; 

    public ContactDAOImpl(DataSource dataSource) { 
     jdbcTemplate = new JdbcTemplate(dataSource); 
    } 

    @Override 
    public void saveOrUpdate(Contact contact) { 
     if (contact.getId() > 0) { 
      // update 
      String sql = "UPDATE contact SET name=?, email=?, address=?, " 
         + "telephone=? WHERE contact_id=?"; 
      jdbcTemplate.update(sql, contact.getName(), contact.getEmail(), 
        contact.getAddress(), contact.getTelephone(), contact.getId()); 
     } else { 
      // insert 
      String sql = "INSERT INTO contact (name, email, address, telephone)" 
         + " VALUES (?, ?, ?, ?)"; 
      jdbcTemplate.update(sql, contact.getName(), contact.getEmail(), 
        contact.getAddress(), contact.getTelephone()); 
     } 

    } 

    @Override 
    public void delete(int contactId) { 
     String sql = "DELETE FROM contact WHERE contact_id=?"; 
     jdbcTemplate.update(sql, contactId); 
    } 

    @Override 
    public List<Contact> list() { 
     String sql = "SELECT * FROM contact"; 
     List<Contact> listContact = jdbcTemplate.query(sql, new RowMapper<Contact>() { 

      @Override 
      public Contact mapRow(ResultSet rs, int rowNum) throws SQLException { 
       Contact aContact = new Contact(); 

       aContact.setId(rs.getInt("contact_id")); 
       aContact.setName(rs.getString("name")); 
       aContact.setEmail(rs.getString("email")); 
       aContact.setAddress(rs.getString("address")); 
       aContact.setTelephone(rs.getString("telephone")); 

       return aContact; 
      } 

     }); 

     return listContact; 
    } 

    @Override 
    public Contact get(int contactId) { 
     String sql = "SELECT * FROM contact WHERE contact_id=" + contactId; 
     return jdbcTemplate.query(sql, new ResultSetExtractor<Contact>() { 

      @Override 
      public Contact extractData(ResultSet rs) throws SQLException, 
        DataAccessException { 
       if (rs.next()) { 
        Contact contact = new Contact(); 
        contact.setId(rs.getInt("contact_id")); 
        contact.setName(rs.getString("name")); 
        contact.setEmail(rs.getString("email")); 
        contact.setAddress(rs.getString("address")); 
        contact.setTelephone(rs.getString("telephone")); 
        return contact; 
       } 

       return null; 
      } 

     }); 
    } 

} 

pom.xml:

<?xml version="1.0" encoding="UTF-8"?> 
<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>net.codejava.spring</groupId> 
    <artifactId>SpringMvcJdbcTemplate</artifactId> 
    <version>1.0</version> 
    <packaging>war</packaging> 

    <name>SpringMvcJdbcTemplate</name> 
    <url>http://maven.apache.org</url> 

    <properties> 
     <java.version>1.8</java.version> 
     <spring.version>4.0.3.RELEASE</spring.version> 
     <cglib.version>2.2.2</cglib.version> 
    </properties> 

    <dependencies> 



     <dependency> 
      <groupId>org.postgresql</groupId> 
      <artifactId>postgresql</artifactId> 
      <version>9.3-1102-jdbc41</version> 
     </dependency> 

     <!-- Spring core & mvc --> 
     <dependency> 
      <groupId>org.springframework</groupId> 
      <artifactId>spring-jdbc</artifactId> 
      <version>${spring.version}</version> 
     </dependency> 

     <dependency> 
      <groupId>org.springframework</groupId> 
      <artifactId>spring-context</artifactId> 
      <version>${spring.version}</version> 
     </dependency> 

     <dependency> 
      <groupId>org.springframework</groupId> 
      <artifactId>spring-webmvc</artifactId> 
      <version>${spring.version}</version> 
     </dependency> 
     <dependency> 
      <groupId>org.springframework</groupId> 
      <artifactId>spring-orm</artifactId> 
      <version>${spring.version}</version> 
      <type>jar</type> 
      <scope>compile</scope> 
     </dependency> 

     <!-- CGLib for @Configuration --> 
     <dependency> 
      <groupId>cglib</groupId> 
      <artifactId>cglib-nodep</artifactId> 
      <version>${cglib.version}</version> 
      <scope>runtime</scope> 
     </dependency> 


     <!-- Servlet Spec --> 
     <dependency> 
      <groupId>javax.servlet</groupId> 
      <artifactId>javax.servlet-api</artifactId> 
      <version>3.1.0</version> 
      <scope>provided</scope> 
     </dependency> 
     <dependency> 
      <groupId>javax.servlet.jsp</groupId> 
      <artifactId>javax.servlet.jsp-api</artifactId> 
      <version>2.3.1</version> 
      <scope>provided</scope> 
     </dependency> 

     <dependency> 
      <groupId>jstl</groupId> 
      <artifactId>jstl</artifactId> 
      <version>1.2</version>  
     </dependency> 




    </dependencies> 

    <build> 
     <finalName>SpringMvcJdbcTemplate</finalName> 
     <plugins> 
      <plugin> 
       <groupId>org.apache.maven.plugins</groupId> 
       <artifactId>maven-compiler-plugin</artifactId> 
       <version>2.0.2</version> 
       <configuration> 
        <source>${java.version}</source> 
        <target>${java.version}</target> 
       </configuration> 
      </plugin> 
     </plugins> 
    </build> 
</project> 
+0

Это в нижней части трассировки стека: «Не удалось загрузить класс драйвера JDBC [org.postgresql.Driver]». Является ли ваш драйвер JDBC на пути к классам? – kryger

+0

Я добавил свой pom.xml, проверьте пожалуйста – GermanSevostyanov

+0

У меня есть зависимость от 9.3-1102-jdbc41 и spring-jdbc 4.0.3.RELEASE – GermanSevostyanov

ответ

0

Попробуйте обновить свой проект, чтобы загрузить все библиотеки, а затем вы увидите абсолютный путь для драйвера postgresql.

+0

Что вы хотите обновить? – GermanSevostyanov

+0

Это проект maven, поэтому вам нужно загрузить все зависимости (все банки). Вы можете обновить свой репозиторий maven, щелкнув правой кнопкой мыши по проекту> Maven> Обновить проект. Я предполагаю, что вы используете eclipse или STS –

+0

, но Я использую IDEA, могу ли я сделать это в IDEA? – GermanSevostyanov

Смежные вопросы