Spring이 존재하는 경우 Bean xml 구성 파일을 찾을 수 없습니다.
Spring에서 첫 번째 빈을 만들려고하는데 컨텍스트를로드하는 데 문제가 있습니다. src / main / resources에 빈의 구성 XML 파일이 있습니다.
다음 IOException이 발생합니다.
스레드 "main"의 예외 org.springframework.beans.factory.BeanDefinitionStoreException : 클래스 경로 리소스 [src / main / resources / beans.xml]에서 XML 문서를 구문 분석하는 IOException; 중첩 된 예외는
java.io.FileNotFoundException : 클래스 경로 리소스 [src / main / resources / beans.xml]이 존재하지 않기 때문에 열 수 없습니다.
하지만 다음 코드 테스트를 수행하기 때문에 이해하지 못합니다.
File f = new File("src/main/resources/beans.xml");
System.out.println("Exist test: " + f.exists());
사실입니다! resources클래스 경로에 있습니다. 뭐가 문제 야?
감사합니다.하지만 그것은 해결책이 아닙니다. 나는 그것이 나를 위해 작동하지 않는 이유를 알았습니다.
선언을 했으므로 :
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
beans.xml 파일이있을 때 프로젝트의 루트 디렉토리를 참조 할 것이라고 생각했습니다. 그런 다음 구성 파일을 src / main / resources에 넣고 초기화를 다음과 같이 변경했습니다.
ApplicationContext context = new ClassPathXmlApplicationContext("src/main/resources/beans.xml");
여전히 IO 예외였습니다.
그런 다음 파일은 src / main / resources /에 남았지 만 선언을 다음과 같이 변경했습니다.
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
문제를 해결했습니다. 누군가에게 도움이 될 수도 있습니다.
감사합니다!
편집하다:
많은 사람들이이 솔루션에 대해 엄지 척하고 몇 년 전 학생으로서 Spring을 처음 경험했기 때문에 이것이 작동하는 이유를 간단히 설명하고 싶습니다.
프로젝트가 컴파일되고 패키징 될 때 프로젝트의 'src / main / java'에있는 모든 파일과 하위 디렉토리는 패키징 된 jar (우리가 만들려는 아티팩트)의 루트 디렉토리로 이동합니다. 'src / main / resources'에도 동일한 규칙이 적용됩니다.
이것은 프로젝트를 빌드하는 과정에서 maven 또는 sbt와 같은 많은 도구에서 존중하는 규칙입니다 (참고 : 기본 구성으로!). 코드 (게시물)가 실행 모드에있을 때 beans.xml이 jar의 루트 (/ beans에 복사 됨)에 있기 때문에 "src / main / resources / beans.xml"과 같은 것을 찾을 수 없습니다. 생성 된 jar / ear / war의 .xml).
ClassPathXmlApplicationContext를 사용할 때 bean xml 정의에 대한 적절한 위치 선언은이 경우 "/beans.xml"이었습니다. 이것은 jar에 있고 나중에 classpath에 속하는 경로이기 때문입니다.
아카이버 (예 : rar)로 jar의 압축을 풀고 디렉토리 구조로 내용을 확인하여 확인할 수 있습니다.
보충으로 classpath에 대한 기사를 읽는 것이 좋습니다.
이 시도:
new ClassPathXmlApplicationContext("file:src/main/resources/beans.xml");
file : 접두사는 클래스 경로가 아닌 파일 시스템 리소스를 가리 킵니다.
파일 경로는 상대 또는 시스템 일 수 있습니다 (/ home / user / Work / src ...).
나도 비슷한 문제가 있었지만 약간 다른 원인으로 인해 누구에게나 도움이 될 수 있도록 여기에 공유하십시오.
내 파일 위치

내가 사용하는 방법
ClassPathXmlApplicationContext("beans.xml");
두 가지 해결책이 있습니다
- 패키지에서 beans.xml을 가져 와서 기본 패키지에 넣으십시오.
- 그것을 사용하는 동안 패키지 이름을 지정하십시오.
ClassPathXmlApplicationContext("com/mypackage/beans.xml");
src/main/resources소스 디렉토리이므로 직접 참조해서는 안됩니다. 프로젝트를 빌드 / 패키징하면 콘텐츠가 클래스 경로의 올바른 위치에 복사됩니다. 그런 다음 다음과 같이로드해야합니다.
new ClassPathXmlApplicationContext("beans.xml")
아니면 이렇게
new GenericXmlApplicationContext("classpath:beans.xml");
그걸 써 ApplicationContext context = new FileSystemXmlApplicationContext("Beans.xml");
이는 applicationContect.xml 또는 any_filename.XML이 적절한 경로에 배치되지 않았기 때문입니다.
문제 해결 단계
1 : 리소스 폴더 아래에 XML 파일을 추가합니다.
2 : 리소스 폴더가없는 경우. 새 프로젝트를 마우스 오른쪽 단추로 클릭하고 새> 소스 폴더를 탐색하여 새로 작성하고 리소스 이름을 지정하고 그 아래에 XML 파일을 배치하십시오.
src 디렉토리를 살펴 보았습니다. xml 파일이 실제로 존재합니다. 그러나 모든 출력 클래스가 설정된 class 또는 bin / build 디렉토리를 살펴보십시오. 사용하려면 resources / beans.xml 경로 만 필요합니다.
나는 당신이 .war / .jar을 만들고 있다고 생각하고 결과적으로 더 이상 파일이 아니라 해당 패키지 내의 리소스입니다. 대신 ClassLoader.getResourceAsStream (String path)을 사용해보십시오 .
첫 번째 applicationContext는의 일부로로드됩니다 web.xml. 아래에 언급되어 있습니다.
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>META-INF/spring/applicationContext.xml</param-value>
</context-param>
<servlet>
<servlet-name>myOwn-controller</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>META-INF/spring/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
아래 코드는 applicationContext를 하나 더 만들려고 시도합니다.
private static final ApplicationContext context =
new ClassPathXmlApplicationContext("beans.xml");
See the difference between beans.xml and applicationContext.xml
And if appliationContext.xml under <META-INF/spring/> has declared with <import resource="beans.xml"/> then this appliationContext.xml is loading the beans.xml under the same location META-INF/spring of appliationContext.xml.
Where as; in the code; if it is declared like below
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
This is looking the beans.xml at WEB-INF/classes OR in eclipse src/main/resources.
[If you have added beans.xml at src/main/resources then it might be placed at WEB-INF/classes while creating the WAR.]
So totally TWO files are looked up.
I have resolved this issue by adding classpath lookup while importing at applicationContext.xml like below
<import resource="classpath*:beans.xml" />
and removed the the line ClassPathXmlApplicationContext("beans.xml") in java code, so that there will be only one ApplicationContext loaded.
In Spring all source files are inside src/main/java. Similarly, the resources are generally kept inside src/main/resources. So keep your spring configuration file inside resources folder.
Make sure you have the ClassPath entry for your files inside src/main/resources as well.
In .classpath check for the following 2 lines. If they are missing add them.
<classpathentry path="src/main/java" kind="src"/>
<classpathentry path="src/main/resources" kind="src" />
So, if you have everything in place the below code should work.
ApplicationContext ctx = new ClassPathXmlApplicationContext("Spring-Module.xml");
I did the opposite of most. I am using Force IDE Luna Java EE and I placed my Beans.xml file within the package; however, I preceded the Beans.xml string - for the ClassPathXMLApplicationContext argument - with the relative path. So in my main application - the one which accesses the Beans.xml file - I have:
ApplicationContext context =
new ClassPathXmlApplicationContext("com/tutorialspoin/Beans.xml");
I also noticed that as soon as I moved the Beans.xml file into the package from the src folder, there was a Bean image at the lower left side of the XML file icon which was not there when this xml file was outside the package. That is a good indicator in letting me know that now the beans xml file is accessible by ClassPathXMLAppllicationsContext.
This is what worked for me:
new ClassPathXmlApplicationContext("classpath:beans.xml");
If this problem is still flummoxing you and you are developing using Eclipse, have a look at this Eclipse bug: Resources files from "src/main/resources" are not correctly included in classpath
Solution seems to be look at properties of project, Java build path, source folders. Delete the /src/main/resources dir and add it again. This causes Eclipse to be reminded it needs to copy these files to the classpath.
This bug affected me when using the "Neon" release of Eclipse. (And was very frustrating until I realized the simple fix just described)
I was experiencing this issue and it was driving me nuts; I ultimately found the following lying in my POM.xml, which was the cause of the problem:
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>**/*.properties</include>
</includes>
</resource>
</resources>
I was not sure to write it but maybe someone save a few hours:
mvn clean
may do the job if your whole configuration is already perfect!
Gradle : v4.10.3
IDE : IntelliJ
I was facing this issue when using gradle to run my build and test. Copying the applicationContext.xml all over the place did not help. Even specifying the complete path as below did not help !
context = new ClassPathXmlApplicationContext("C:\\...\\applicationContext.xml");
The solution (for gradle at least) lies in the way gradle processes resources. For my gradle project I had laid out the workspace as defined at https://docs.gradle.org/current/userguide/java_plugin.html#sec:java_project_layout
When running a test using default gradle set of tasks includes a "processTestResources" step, which looks for test resources at C:\.....\src\test\resources (Gradle helpfully provides the complete path).
Your .properties file and applicationContext.xml need to be in this directory. If the resources directory is not present (as it was in my case), you need to create it copy the file(s) there. After this, simply specifying the file name worked just fine.
context = new ClassPathXmlApplicationContext("applicationContext.xml");
'Nice programing' 카테고리의 다른 글
| Maven의 외부 라이브러리가있는 Android Studio에서 네임 스페이스 '앱'이 바인딩되지 않았습니다. (0) | 2020.11.12 |
|---|---|
| HH : MM : SS 형식의 시간을 초로 만 변환 하시겠습니까? (0) | 2020.11.12 |
| Android Studio 인수에 대한 runProguard () 메서드를 찾을 수 없습니까? (0) | 2020.11.12 |
| Spark의 CSV 파일에서 헤더를 건너 뛰려면 어떻게하나요? (0) | 2020.11.12 |
| 프로그래밍 방식으로 Android 앱을 종료하는 방법은 무엇입니까? (0) | 2020.11.12 |