Соответствующий шаблон является строгим, но для элемента ‘tx: annotation-driven’

Я пытаюсь настроить JSF + Spring + hibernate, и я привязываюсь для запуска теста, но когда я использую этот «tx: annotation-driven» в моем файле application-context.xml, я получаю эту ошибку:

Соответствующий шаблон является строгим, но для элемента ‘tx: annotation-driven’

Вот мой application-context.xml:

            om.mycompany.model.Course om.mycompany.model.Student om.mycompany.model.Teacher     org.hibernate.dialect.OracleDialect           

и вот мой CourseServiceImplTest. Я еще не реализовал тесты:

 public class CourseServiceImplTest { private static ClassPathXmlApplicationContext context; private static CourseService courseService; public CourseServiceImplTest() { } @BeforeClass public static void setUpClass() throws Exception { context=new ClassPathXmlApplicationContext("application-context.xml"); courseService=(CourseService) context.getBean("courseService"); } @AfterClass public static void tearDownClass() throws Exception { context.close(); } @Before public void setUp() { } @After public void tearDown() { } /** * Test of getAllCourses method, of class CourseServiceImpl. */ @Test public void testGetAllCourses() { System.out.println("getAllCourses"); CourseServiceImpl instance = new CourseServiceImpl(); List expResult = null; List result = instance.getAllCourses(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of getCourse method, of class CourseServiceImpl. */ @Test public void testGetCourse() { System.out.println("getCourse"); Integer id = null; CourseServiceImpl instance = new CourseServiceImpl(); Course expResult = null; Course result = instance.getCourse(id); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } 

и вот CourseServiceImpl:

 @Service("courseService") @Transactional public class CourseServiceImpl implements CourseService{ @Autowired private SessionFactory sessionFactory; @Override public List getAllCourses() { return sessionFactory.getCurrentSession().createQuery("from Course").list(); } @Override public Course getCourse(Integer id) { return (Course) sessionFactory.getCurrentSession().get(Course.class, id); } @Override public void save(Course course) { sessionFactory.getCurrentSession().saveOrUpdate(course); } } 

У вас есть некоторые ошибки в вашем appcontext.xml:

  • Использовать * -2.5.xsd

     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd" 
  • Typos в tx:annotation-driven и context:component-scan (вместо -)

       

Это для других (как я :)). Не забудьте добавить зависимость пружины tx jar / maven. Также правильная конфигурация в appctx:

 xmlns:tx="http://www.springframework.org/schema/tx" 

xsi:schemaLocation="http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"

, по ошибке неправильная конфигурация, которую другие могут иметь

 xmlns:tx="http://www.springframework.org/schema/tx/spring-tx-3.1.xsd" 

то есть дополнительный «/spring-tx-3.1.xsd»

xsi:schemaLocation="http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"

другими словами, что есть в xmlns (namespace) должно иметь правильное отображение в schemaLocation (namespace vs schema).

пространство имен: http://www.springframework.org/schema/tx

Схема Doc пространства имен: http://www.springframework.org/schema/tx/spring-tx-3.1.xsd

эта схема пространства имен позже отображается в банке, чтобы найти путь к фактическому xsd, расположенному в org.springframework.transaction.config

Для меня все, что сработало, – это порядок, в котором пространства имен были определены в теге xsi: schemaLocation: [поскольку версия была хороша, а также уже был менеджером транзакций]

Ошибка была связана с:

  http://www.springframework.org/schema/mvc http://www.springframework.org/schema/tx http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/tx/spring-tx-3.0.xsd" 

И ПОСТАНОВИЛИ:

 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd" 

В моем случае это было фактически симптомом сервера, размещенного на AWS, без IP для внешней сети. Он попытается загрузить пространства имен с сайта springframework.org и не сможет установить соединение.

FWIW У меня была эта же проблема. Оказалось, что мои xsi: schemaLocation были неверными, поэтому я пошел в официальные документы и вставил их в свою:

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/transaction.html раздел 16.5.6

Мне пришлось добавить еще пару, но все было в порядке. Далее нужно выяснить, почему это устранило проблему …

Убедитесь, что версия Spring и версия xsd одинаковы. В моем случае я использую Spring 4.1.1, поэтому мой xsd должен быть версией * -4.1.xsd

Одна дополнительная передняя косая черта (/) перед tx и файлом * .xml беспокоили меня в течение 8 часов!

Виноват:

 http://www.springframework.org/schema/tx/ http://www.springframework.org/schema/tx/spring-tx-4.3.xsd 

Исправление:

 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd 

Действительно, одному персонажу все меньше и больше удается удерживать программистов в течение нескольких часов!

Я учусь от удемий. Я следовал за каждым шагом, который показал мне мой инструктор. В весенней секции mvc crud при настройке среды разработки я имел ту же ошибку:

  and  

то я просто заменил

  http://www.springframework.org/schema/mvc/spring-mvc.xsd 

с

  http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd 

а также

  http://www.springframework.org/schema/tx/spring-tx.xsd 

с

  http://www.springframework.org/schema/tx/spring-tx-4.2.xsd 

на самом деле я посетил эти два сайта http://www.springframework.org/schema/mvc/ и http://www.springframework.org/schema/tx/ и просто добавил последнюю версию spring-mvc и spring-tx ie , spring-mvc-4.2.xsd и spring-tx-4.2.xsd

Поэтому я предлагаю попробовать это. Надеюсь это поможет. Спасибо.

 Any one can help for me!!!!!!!!!   (ERROR OCCUR)  (ERROR OCCUR)               classpath:hibernate.cfg.xml   org.hibernate.cfg.AnnotationConfiguration    ${org.hibernate.dialect.MySQLDialect} true       (ERROR OCCUR)     
  • Вам нужна транзакция базы данных для чтения данных?
  • Oracle: как узнать, ожидает ли транзакция?
  • Каков уровень изоляции транзакций по умолчанию для SQL Server с ADO.NET?
  • Как использовать TransactionScope в C #?
  • TransactionScope автоматически переходит на MSDTC на некоторых машинах?
  • Где принадлежит аннотация @Transactional?
  • EJB 3.0 - Вложенная транзакция! = Требуется Новое?
  • Как откатить транзакцию базы данных при тестировании служб с помощью Spring в JUnit?
  • Каков «лучший» способ делать распределенные транзакции в нескольких базах данных с использованием Spring и Hibernate
  • TransactionScope с файлами в C #
  • Как TransactionScope откатывает транзакции?
  • Interesting Posts

    Перенос Windows 8.1 в начало диска

    ВСЕГДА отображает последний / стандартный пользовательский экран приветствия Windows 7

    Почему BCL GZipStream (с StreamReader) не надежно обнаруживает ошибки данных с помощью CRC32?

    Установить цвет области TextView в Android

    Доступ запрещен для пользователя root @ localhost ‘(с использованием пароля: НЕТ)

    aapt не найден по правильному пути

    Есть ли простой способ предварительной обработки и перенаправления запросов GET?

    Быстрая сортировка Наихудший случай

    Bitlocker не запрашивает пароль?

    Регулярное выражение для проверки пароля: «8 символов, включая 1 прописную букву, 1 специальный символ, буквенно-цифровые символы»

    Как установить соединение по коммутируемому соединению автоматически после загрузки + загрузки 90 МБ данных в Windows?

    Просмотр полных строк при отладке в Eclipse

    Как заставить скрипт запускаться при запуске машины Ubuntu?

    Прослушать запрос wakeonlan

    MPI_Rank возвращает тот же номер процесса для всех процессов

    Давайте будем гением компьютера.