Соответствующий подстановочный знак является строгим, но не найдено никакого объявления для элемента 'tx: annotation-driven' - PullRequest
42 голосов
/ 19 мая 2011

Я пытаюсь настроить 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);
    }

}

Ответы [ 9 ]

50 голосов
/ 19 мая 2011

В вашем appcontext.xml есть ошибки:

14 голосов
/ 12 января 2013

Это для других (таких как я :)).Не забудьте добавить зависимость 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"

, т. Е. 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 (пространство имен), должно иметь правильное отображение в schemaLocation (пространство имен против схемы).

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

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

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

10 голосов
/ 13 сентября 2013

Для меня сработало то, в каком порядке были определены пространства имен в теге 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"
1 голос
/ 08 июня 2018

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

1 голос
/ 17 ноября 2016

Одна дополнительная косая черта (/) перед 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

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

0 голосов
/ 31 марта 2018
Any one can help for me!!!!!!!!!
<?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:jee="http://www.springframework.org/schema/jee"
        xmlns:lang="http://www.springframework.org/schema/lang"
        xmlns:p="http://www.springframework.org/schema/p"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:util="http://www.springframework.org/schema/util"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/aop/ http://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/context/ http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/jee/ http://www.springframework.org/schema/jee/spring-jee.xsd
            http://www.springframework.org/schema/lang/ http://www.springframework.org/schema/lang/spring-lang.xsd
            http://www.springframework.org/schema/tx/ http://www.springframework.org/schema/tx/spring-tx.xsd
            http://www.springframework.org/schema/util/ http://www.springframework.org/schema/util/spring-util.xsd">
        <context:annotation-config />(ERROR OCCUR)
        <context:component-scan base-package="hiberrSpring" /> (ERROR OCCUR)
        <bean id="jspViewResolver"
            class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="viewClass"
                value="org.springframework.web.servlet.view.JstlView"></property>
            <property name="prefix" value="/WEB-INF/"></property>
            <property name="suffix" value=".jsp"></property>
        </bean>
        <bean id="messageSource"
            class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
            <property name="basename" value="classpath:messages"></property>
            <property name="defaultEncoding" value="UTF-8"></property>
        </bean>
        <bean id="propertyConfigurer"
            class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
            p:location="/WEB-INF/jdbc.properties"></bean>
        <bean id="dataSource"
            class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
            p:driverClassName="${com.mysql.jdbc.Driver}"
            p:url="${jdbc:mysql://localhost/}" p:username="${root}"
            p:password="${rajini}"></bean>
        <bean id="sessionFactory"
            class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
            <property name="dataSource" ref="dataSource"></property>
            <property name="configLocation">
                <value>classpath:hibernate.cfg.xml</value>
            </property>
            <property name="configurationClass">
                <value>org.hibernate.cfg.AnnotationConfiguration</value>
            </property>
            <property name="hibernateProperties">
                <props>
                    <prop key="hibernate.dialect">${org.hibernate.dialect.MySQLDialect}</prop>
                    <prop key="hibernate.show_sql">true</prop>
                </props>
            </property>
        </bean>
        <bean id="employeeDAO" class="hiberrSpring.EmployeeDaoImpl"></bean>
        <bean id="employeeManager" class="hiberrSpring.EmployeeManagerImpl"></bean>
        <tx:annotation-driven /> (ERROR OCCUR)
        <bean id="transactionManager"
            class="org.springframework.orm.hibernate3.HibernateTransactionManager">
            <property name="sessionFactory" ref="sessionFactory"></property>
        </bean>
    </beans>
0 голосов
/ 15 ноября 2017

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

<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, т.е. spring-mvc-4.2.xsd и spring-tx-4.2.xsd

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

0 голосов
/ 31 января 2016

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

0 голосов
/ 10 ноября 2015

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

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

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...