Исключение нулевого указателя - это индикатор того, что вы используете объект, не инициализируя его.
Например, ниже - класс ученика, который будет использовать его в нашем коде.
public class Student {
private int id;
public int getId() {
return this.id;
}
public setId(int newId) {
this.id = newId;
}
}
Приведенный ниже код дает вам исключение с нулевым указателем.
public class School {
Student obj_Student;
public School() {
try {
obj_Student.getId();
}
catch(Exception e) {
System.out.println("Null Pointer ");
}
}
}
Поскольку вы используете Obj_Student
, но вы забыли инициализировать его, как в правильном коде, показанном ниже:
public class School {
Student obj_Student;
public School() {
try {
obj_Student = new Student();
obj_Student.setId(12);
obj_Student.getId();
}
catch(Exception e) {
System.out.println("Null Pointer ");
}
}
}
Вы не указали расположение схемы пространства имен контекста, что является причиной этой конкретной ошибки:
<beans .....
xmlns:context="http://www.springframework.org/schema/context"
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/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
Этот путь расположения схемы неверен:
http://www.springframework.org/schema/beans
Правильный путь должен заканчиваться на /
:
http://www.springframework.org/schema/beans/
Если вы используете STS , вы можете в Eclipse пометить файл конфигурации как файл конфигурации «Bean Configuration» (вы можете указать, что при создании или щелчке правой кнопкой мыши по XML-файлу):
У проекта должен быть Spring Nature (например, правый клик на проекте maven):
, тогда spring.xml
открывается по умолчанию с помощью редактора Spring Config
, и этот редактор имеет вкладку Пространства имен
Позволяет указать пространства имен:
Обратите внимание, что это зависит на зависимостях (с использованием проекта maven), поэтому, если spring-tx
не задано в p.m.xml maven, опция отсутствует, что предотвращает наличие Подстановочный шаблон является строгим, но для элемента ' tx: связанная с аннотацией проблема «контекст: компонент-сканирование» ...
spring-web
зависимости в помпе
– ring bearer
13 August 2015 в 13:07
С объявлением пространства имен и расположением схемы вы также можете проверить синтаксис использования пространства имен, например: -
<beans xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation= http://www.springframework.org/`enter code here`schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-driven/> <!-- This is wrong -->
<context:annotation-config/> <!-- This should work -->
Это слишком поздно, но может быть полезно другим
Соответствующий шаблон является строгим, но для контекста элемента не найдено объявления: компонент-сканирование
, который означает, что вы пропустили некоторые объявления или требуемые декларации, не найденные в вашем XML
В моем случае я забыл добавить следующее
- http: //www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
- http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx /spring-tx-4.0.xsd
После добавления этой проблемы ушел
<?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd 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/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
Эта ошибка также может быть вызвана, если файл jar, содержащий необходимый XSD, не включен в ваш путь к развертываемому классу.
Убедитесь, что зависимости доступны в вашем контейнере.
Правильный путь не должен заканчиваться на «/», я ошибался, что вызвало проблему
Правильный путь:
http: //www.springframework .org / schema / context http://www.springframework.org/schema/context/spring-context.xsd
, когда вы добавляете контекст: компонент-сканирование в первый раз в xml, необходимо добавить следующее:
xmlns:context="http://www.springframework.org/schema/context"
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">