Соответствующий шаблон является строгим, но для элемента 'tx: annotation-driven'
Я пытаюсь настроить JSF + Spring + hibernate, и я привязываюсь для запуска теста, но когда я использую этот "tx: annotation-driven" в моем файле application-context.xml, я получаю эту ошибку:
Соответствующий шаблон является строгим, но для элемента 'tx: annotation-driven' не найдено объявления
Вот мой application-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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
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.6.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.6.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.6.xsd
" xmlns:tool="http://www.springframework.org/schema/tool">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:@192.168.56.101:1521:Gpsi"/>
<property name="username" value="omar"/>
<property name="password" value="omar"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="annotatedClasses">
<list>
<value>om.mycompany.model.Course</value>
<value>om.mycompany.model.Student</value>
<value>om.mycompany.model.Teacher</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<tx:annotation-driven transaction.manager="transactionManager"/>
<context:annotation-config/>
<context:component-scan base.package="com.mmycompany"/>
</beans>
и вот мой курс 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<Course> 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);
}
}
Ответы
Ответ 1
У вас есть некоторые ошибки в вашем 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:annotation-driven transaction-manager="transactionManager" />
<context:component-scan base-package="com.mmycompany" />
Ответ 2
Это для других (как я:)). Не забудьте добавить spring 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"
i.e., extra "/ 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 здесь: http://www.springframework.org/schema/tx
Схема Doc пространства имен: http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
эта схема пространства имен позже отображается в банке, чтобы найти путь к фактическому xsd, расположенному в org.springframework.transaction.config
Ответ 3
Для меня все, что сработало, - это порядок, в котором пространства имен были определены в теге 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"
Ответ 4
FWIW У меня была такая же проблема. Оказалось, что мои xsi: schemaLocation были неверными, поэтому я пошел в официальные документы и вложил их в свою:
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/transaction.html раздел 16.5.6
Мне пришлось добавить еще пару, но все было в порядке. Затем нужно выяснить, почему это устранило проблему...
Ответ 5
Убедитесь, что версия Spring и версия xsd одинаковы. В моем случае я использую Spring 4.1.1, поэтому все мои xsd должны быть версии * -4.1.xsd
Ответ 6
Одна дополнительная косая черта (/) перед 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
Действительно, одному персонажу все меньше и больше удается удерживать программистов в течение нескольких часов!
Ответ 7
Я учусь от udemy. Я следовал за каждым шагом, который показал мне мой инструктор.
В разделе spring mvc crud при настройке среды devlopment у меня была такая же ошибка для:
<mvc:annotation-driven/> and <tx:annotation-driven transaction-manager="myTransactionManager" />
то я просто заменил
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 i.e, spring -mvc-4.2.xsd и spring -tx-4.2.xsd
Итак, я предлагаю попробовать это.
Надеюсь это поможет.
Спасибо.