2016-11-16 3 views
0

Я пытаюсь создать простой проект весеннего отдыха с зимним спящим режимом.Создание проекта спящего режима с весенним отдыхом

Я сделал DAO и сервисный слой. Я также сконфигурировал beans-компоненты в диспетчер-сервлете и автопрововал в классе контроллера с сервисом и в сервисе DAO-сессии фабрики и транзакций.

Но я постоянно получаю ошибки.

Я также добавил фотографию ошибки.

dispatcher-servlet.xml: 
<?xml version="1.0" encoding="UTF-8"?> 
beans:beans xmlns:beans="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" 
    xmlns:tx="http://www.springframework.org/schema/tx" 

    xsi:schemaLocation="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 
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd 
     http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> 
<!-- <mvc:annotation-driven /> --> 

<!-- <resources mapping="/resources/**" location="/resources/" /> --> 

<!--JDBC ko properties--> 
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" 
     destroy-method="close"> 
    <beans:property name="driverClassName" value="com.mysql.jdbc.Driver" /> 
    <beans:property name="url" value="jdbc:mysql://localhost:3306/student_database" /> 
    <beans:property name="username" value="root" /> 
    <beans:property name="password" value="" /> 
</beans:bean> 

<!-- Hibernate ko SessionFactory Bean definition part --> 
<beans:bean id="hibernate5AnnotatedSessionFactory" 
     class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> 
    <beans:property name="dataSource" ref="dataSource" /> 
<!--  <beans:property name="annotatedClasses"> 
     <beans:list> 
      <beans:value>com.mycompany.SpringRestMaven.bean</beans:value> 
     </beans:list> 
    </beans:property> --> 
    <beans:property name="hibernateProperties"> 
     <beans:props> 
      <beans:prop  key="hibernate.dialect">org.hibernate.dialect.MySQLDialect 
      </beans:prop> 
      <beans:prop key="hibernate.show_sql">true</beans:prop> 
     </beans:props> 
    </beans:property> 
</beans:bean> 

<context:component-scan base- package="com.mycompany.SpringRestMaven.controller"/> 
<tx:annotation-driven transaction-manager="transactionManager"/> 

<beans:bean id="transactionManager"  class="org.springframework.orm.hibernate4.HibernateTransactionManager"> 
    <beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" /> 
</beans:bean> 

controller class: 
package com.mycompany.SpringRestMaven.controller; 
/* I have not included imports*/ 
@RestController 
public class StudentController { 

@Autowired 
ServiceLayer studentService; 

@RequestMapping(value = "/insert", method = RequestMethod.POST, headers = "Accept=application/json") 
public void insert(@RequestBody Student student) { 
    studentService.insert(student); 
} 

@RequestMapping(value = "/update", method = RequestMethod.PUT, headers = "Accept=application/json") 
public void update(@RequestBody Student student) { 
    studentService.update(student); 
} 

@RequestMapping(value = "/delete", method = RequestMethod.DELETE, headers = "Accept=application/json") 
public void delete(@PathVariable("id") int id) { 
    studentService.delete(id); 
} 

@RequestMapping(value = "/getAll", method = RequestMethod.GET, headers = "Accept=application/json") 
public List<Student> getAll() { 

    List<Student> listOfStudent = studentService.getAll(); 
    return listOfStudent; 
} 

@RequestMapping(value = "/searchById/{id}", method = RequestMethod.GET, headers = "Accept=application/json") 
public Student searchById(@PathVariable int id) { 
    return studentService.searchById(id); 
} 
} 

This is my service layer implementation: 

package com.mycompany.SpringRestMaven.Service; 

@Service("studentService") 
public class ServiceImpl implements ServiceLayer { 

@Autowired StudentDAO studentDao; 

@Transactional 
@Override 
public void insert(Student s) { 
    studentDao.insert(s); 
} 

@Transactional 
@Override 
public void update(Student s) { 
    studentDao.update(s); 
} 

@Transactional 
@Override 
public void delete(int id) { 
    studentDao.delete(id); 
} 

@Transactional 
@Override 
public List<Student> getAll() { 
    return studentDao.getAll(); 
} 

@Transactional 
@Override 
public Student searchById(int id) { 
    return studentDao.searchById(id); 
} 

} 

This is my DAO implementation: 

package com.mycompany.SpringRestMaven.DAO; 

@Repository 
public class StudentDAOImpl implements StudentDAO { 

@Autowired 
private SessionFactory sessionFactory; 
private Session session; 
private Transaction trans; 

@Override 
public void insert(Student s) { 
    session = sessionFactory.openSession(); 
    trans = session.beginTransaction(); 
    session.save(s); 
    trans.commit(); 
    session.close(); 
} 

@Override 
public void update(Student s) { 
    session = sessionFactory.openSession(); 
    trans = session.beginTransaction(); 
    session.saveOrUpdate(s); 
    trans.commit(); 
    session.close(); 
} 

@Override 
public void delete(int id) { 
    session = sessionFactory.openSession(); 
    trans = session.beginTransaction(); 
    Student sObject = (Student) session.get(Student.class, id); 
    session.delete(sObject); 
    trans.commit(); 
    session.close(); 
} 

@Override 
public List<Student> getAll() { 
    return session.createQuery("SELECT s FROM Student s").list(); 
} 

@Override 
public Student searchById(int id) { 
    return (Student) session.get(Student.class, id); 
} 


} 

Я получаю эту ошибку:

screenshot

+0

не видел вашу ошибку! –

+0

Ошибка говорит, что весна не могла найти bean-тип типа ServiceLayer. – smsnheck

+0

Измените базу развертки компонентов на com.mycompany.SpringRestMaven. С вашей текущей конфигурацией он не смог найти Beans, которые не находятся в пакете контроллера. – smsnheck

ответ

0

изменить конфигурацию

<context:component-scan base- package="com.mycompany.SpringRestMaven.controller"/> 

Для

<context:component-scan base- package="com.mycompany.SpringRestMaven"/> 

Затем Spring сканирует все ваши классы под пакетом SpringRestMaven и создает бобы из аннотированных классов.

В вашей текущей конфигурации Spring только сканирует и создает компоненты из-под пакета .controller. Ваш ServiceLayer не находится в этом пакете, и поэтому Spring не смог найти класс, не создал компонент и не смог автоувеличивать поле.

+0

Спасибо, сэр, я вас просил. На самом деле я делал это только ранее, но я получал эту ошибку, пожалуйста, посмотрите: – prithivi

+0

Суровый: исключение при загрузке приложения: .ConflictingBeanDefinitionException: имя компонента, указанное в аннотации «webController» для класса bean [com.mycompany.SpringRestMaven.WebController ] конфликтует с существующим, несовместимым компонентом определения того же имени и класса [com.mycompany.SpringRestMaven.controller.WebController] – prithivi

+0

Хорошо выглядит, что у вас есть два класса с именем 'WebController' (в разных пакетах)? – smsnheck