[Solved]-Java file outside of source root intelliJ-Springboot

[Solved]-Java file outside of source root intelliJ-Springboot Техника

Solution 1

If you do an ‘import from git’, IntelliJ doesn’t import the project structure from maven (or gradle) automatically.

One way to do this afterwards is to right-click on the pom.xml file in the root directory, and select ‘Add as maven project’. Then the folders will be marked correctly, and dependent libraries will be imported. There should be no need to mark individual source folders manually.

I prefer to do a git clone outside of IntelliJ, and open the project from the local filesystem, then IntelliJ imports the maven project structure automatically.

Solution 2

Very simple solution :-

Click on «maven» on the right toolbar in IntelliJ and then click on the refresh button.

Solution 3

This has been driving me quite mad and I am a newbie as well. I finally solved it by using:

Then going to Modules and removing all the files from the root using the x marks on the far right. I then used the +Add Content Root to reselect the src folders that contained my .java and hit Apply. Finally InteliJ sees the files as in the project and the folders gain the blue square on the main view.

Solution 4

I fixed it using this way:

and then marked java files dir as Sources.

Solution 5

I prefer to do a git clone outside of IntelliJ, and afterwards open the project in IntelliJ from the local filesystem, then IntelliJ imports the maven project structure automatically.

I’m just gonna throw my solution to this problem in here, since none of the above worked:

If there are multiple pom files in your project, on the Maven sidebar to the right, click the plus (‘+’) button and navigate to the other pom file that does not have the Maven (‘M’) icon next to it in the project structure of your project (left sidebar).

Then click ‘OK’ — this then loads all the Maven dependencies from the unused pom file and, for me, everything was finally fixed!

I had to open the module I worked on to a new window to solve that.

Hate to add yet another method; but this one worked for me after trying and failing with the above methods.
I had a multi-mode project.
Unlinked all maven projects in Maven workspace and reloaded as maven project by clicking root poom.xml in project workspace.
Not sure whether this will always work and for everyone.

IntelliJ may be ignoring files from a multi-module project. Modules that are ignored will make it harder for the IDE to find the root of that file. Hence, java file outside of source root

Now, uncheck the modules you do not want IntelliJ to ignore.

I faced the same problem in one of the modules in my multi module maven project. In my InteliJ idea, I’ve installed Maven Helper plugin before. I did right click on the module and within that contextual menu click Run Maven and then Reimport. After doing that, my issue resolved.

Then everythings worked..

I did a ‘Maven reload’ (or Gradle reload) from the upper-right ‘Maven’ (‘Gradle’) window and problem is solved.

Regenerate Maven Sources and Update Folders

When moving the project from one directory to another, Maven will need to regenerate the sources to tell the project to use Annotation Processing.

Try this

The project should now run

Here’s an image of what the menu looks like for me, in May 2022, as the answers have seemed to vary over time:

[Solved]-Java file outside of source root intelliJ-Springboot

I’m having a similar issue for an Android project in Android Studio Chipmunk 2021.2.1 Patch 1. It looks like a known bug related to using manifest.srcFile: https://issuetracker.google.com/issues/218370114?hl=ko

Apparently the options are switching to the canary channel or waiting for the fix to be released on the stable channel. Or getting rid of manifest.srcFile in your build.gradle.

In intellij:
click Maven,
select the project and right,
select Unignore Projects

For ppl like me who also see that the POM file is crossed out and greyed(ignored):

You can right click the POM.xml, select «Maven — Unignore projects».

«Java file outside of source root»

[Solved]-Java file outside of source root intelliJ-Springboot

First of all, let’s start with the basics. What does this error even mean? Simply put, it means that your Java file is located outside of the designated source root folder. This may happen if you move or copy your file to another location outside of the specified source root. The source root folder is where your source code is stored, and it is typically identified by your IDE (Integrated Development Environment) or build system.

Дополнительно:  Не горят индикаторы на ноутбуке?

Now that we know what the problem is, how do we fix it? Well, there are several ways to go about it. One quick and easy solution is to simply move the affected Java file back to its original location within the source root folder. This may require updating any import statements or package declarations to reflect the new file path.

Another solution is to update your IDE or build system to recognize the new file location as part of the source root. This can typically be done by adjusting project settings or configurations. For example, in IntelliJ IDEA, you can right-click on the new file location and select “Mark Directory as” then select “Sources Root”.

But what if the file location is correct, and you’re still getting the error? Well, there may be an issue with the build path or classpath. The build path is the set of directories or JAR files that your project dependencies are located in, while the classpath is the locations where your compiled classes are stored, as well as any external libraries or JAR files that your project depends on.

If your build path or classpath is incorrect, your IDE or build system may not be able to find your Java file. To resolve this issue, you may need to update your build configuration or dependencies to properly include the required directories or JAR files.

Additional Tips

Now that we’ve covered the basics, let’s dive a little deeper into some additional tips and tricks for dealing with the “Java file outside of source root” error.

Firstly, it is always a good idea to keep your code organized and structured within the source root folder. This will help to avoid any confusion or errors when moving or copying files between different directories. It is also important to regularly clean and rebuild your project to ensure that all dependencies and configurations are up-to-date and accurate.

Secondly, you may want to consider using a version control system such as Git or SVN to track changes to your code and manage multiple versions of your project. This can help to prevent issues with lost or overwritten code, and can also make it easier to collaborate with other developers on your team.

In summary, dealing with the “Java file outside of source root” error may require a little bit of troubleshooting and experimentation, but with the right tools and resources, you can easily overcome this issue and continue coding with confidence. So don’t give up, keep learning, and happy coding!

“Java file outside of source root” is a common error message in IntelliJ IDEA. It simply said that you need to add the file to the project root before doing anything.

For those who are beginning with Java, the error might become a little trouble. In this short article, we will list a few quick fixes for “Java file outside of source root”.

[Solved]-Java file outside of source root intelliJ-Springboot

Import the module from pom. xml for Maven projects

If you’re working on a Maven project, you would have to import import the module from pom.xml so that it configures the roots automatically.

Sources root is marked in blue in the project view. Here is the example of the properly configured project.

[Solved]-Java file outside of source root intelliJ-Springboot

In order to add a Maven module to the project in which you are already working.

Manually mark a folder as source root

Alternatively, you can manually set a folder to be the source root from the sidebar of IntelliJ.

[Solved]-Java file outside of source root intelliJ-Springboot

You can also do this by configuring project modules:

[Solved]-Java file outside of source root intelliJ-Springboot

[Solved]-Java file outside of source root intelliJ-Springboot

Alternatively, you can use the Maven sidebar and click on the folder with spinner icon to activate Generate Sources and Update Folders for All Projects.

[Solved]-Java file outside of source root intelliJ-Springboot

If none of the above solutions worked, here’s a few more suggestions:

Having read to the end of this article, it is clear that you’re getting started with Java. In that case, No string-argument constructor/factory method to deserialize from string value is another common error in Spring Framework which you might find interesting to find out more about.

[Solved]-Java file outside of source root intelliJ-Springboot

IDEA file appears java file out of source root solution

Because this problem has appeared several times, but I have forgotten how to solve it, I hereby publish a blog to deepen my impression.

Intelligent Recommendation

[Solved]-Java file outside of source root intelliJ-Springboot

Java file display J solution

[Solved]-Java file outside of source root intelliJ-Springboot

Idea import project, java file gray solution

[Solved]-Java file outside of source root intelliJ-Springboot

IDEA Select Source (Java) instead of (Class file)

[Solved]-Java file outside of source root intelliJ-Springboot

Python running file appears out of memory box

Я клонировал проект весенней загрузки из GitLab, имеющий несколько веток в IntelliJ. Я оформляю заказ в филиал, в котором хочу работать. Но я получаю «файл Java за пределами исходного корня» для всех файлов. Пожалуйста, подскажите, что я делаю не так. Я только что установил IntelliJ, и это первый проект, который я импортирую.

Дополнительно:  Root top com

Ответов

Если вы выполняете «импорт из git», IntelliJ не импортирует структуру проекта из maven (или gradle) автоматически.

Один из способов сделать это впоследствии — щелкнуть правой кнопкой мыши файл pom.xml в корневом каталоге и выбрать «Добавить как проект maven». Тогда папки будут правильно помечены, и зависимые библиотеки будут импортированы. Не должно быть необходимости вручную отмечать отдельные исходные папки.

Я предпочитаю делать клон git вне IntelliJ и открывать проект из локальной файловой системы, а затем IntelliJ автоматически импортирует структуру проекта maven.

Очень простое решение:-

Нажмите «maven» на правой панели инструментов в IntelliJ, а затем нажмите кнопку обновления.

Я исправил это следующим образом:

а затем пометил java files dir как Sources.

Это сводило меня с ума, и я тоже новичок. Я наконец решил это, используя:

Затем перейдите в Модули и удалите все файлы из корня с помощью значков x справа. Затем я использовал +Add Content Root, чтобы повторно выбрать папки src, содержащие мой.java, и нажать «Применить». Наконец, InteliJ видит файлы как в проекте, а папки выделяются синим квадратом в главном окне.

«Файл Java вне исходного корня»

26 янв ’21 в 20:19

потом все заработало..

Для таких людей, как я, которые также видят, что файл POM вычеркнут и выделен серым цветом (игнорируется):

Вы можете щелкнуть правой кнопкой мыши файл POM.xml и выбрать «Maven — Unignore projects».

Регенерация исходников Maven и папок обновлений

При перемещении проекта из одного каталога в другой Maven потребуется повторно сгенерировать исходные коды, чтобы указать проекту использовать обработку аннотаций.

Попробуй это

Теперь проект должен работать

Вот изображение того, как выглядит меню для меня в мае 2022 года, поскольку ответы со временем менялись:

[Solved]-Java file outside of source root intelliJ-Springboot

Удалите весь модуль и нажмите кнопку «Добавить», затем выберите «Импортировать модуль», выберите корневой файл maven pom.xml вашего проекта.

Это сэкономило мое время.

Я сделал «перезагрузку Maven» (или перезагрузку Gradle) из правого верхнего окна «Maven» («Gradle»), и проблема решена.

IntelliJ может игнорировать файлы из многомодульного проекта. Модули, которые игнорируются, затрудняют для IDE поиск корня этого файла. Следовательно,
java file outside of source root

Теперь снимите флажки с модулей, которые IntelliJ не должен игнорировать.

У меня аналогичная проблема с проектом Android в Android Studio Chipmunk 2021.2.1 Patch 1. Похоже на известную ошибку, связанную с использованием: https://issuetracker.google.com/issues/218370114?hl=ko

Видимо варианты переключаются на канареечный канал или ждут выхода фикса на стабильном канале. Или избавиться отmanifest.srcFileв вашейbuild.gradle.

Щелкните правой кнопкой мыши pom.xml, затем щелкните «maven» и перезагрузите проект.

24 фев ’21 в 14:54

Использование связанного пути Maven 3 решило эту проблему, и приложение Spring Boot запустилось нормально.

Просто для тех, у кого есть незначительная ошибка, которая была у меня:

Моя простая проблема и исправление заключались в том, чтобы перейти в тот файл, который я клонировал. Я случайно открыл родительский каталог с идеей. вместо проекта, над которым мне нужно было работать.

Пожалуйста, выполните следующие 2 шага:

Ненавижу добавлять еще один метод; но этот сработал для меня после попытки и неудачи с вышеуказанными методами. У меня был многорежимный проект. Отключены все проекты maven в рабочей области Maven и перезагружены как проект maven, щелкнув root poom.xml в рабочей области проекта. Не уверен, что это будет работать всегда и для всех.

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

Я столкнулся с той же проблемой в одном из модулей моего мультимодуля.
mavenпроект. В моем
InteliJидея, я установил
Maven Helperплагин раньше. Я щелкнул правой кнопкой мыши по модулю и в этом контекстном меню выбрал « Запустить Maven» , а затем «Повторно импортировать» . После этого моя проблема решилась.

Я просто брошу здесь свое решение этой проблемы, поскольку ничего из вышеперечисленного не сработало:

Если в вашем проекте несколько файлов pom, на боковой панели Maven справа нажмите кнопку с плюсом (‘+’) и перейдите к другому файлу pom, рядом с которым нет значка Maven (‘M’) в структура вашего проекта (левая боковая панель).

Затем нажмите «ОК» — это загрузит все зависимости Maven из неиспользуемого файла pom, и для меня все, наконец, было исправлено!

Открытый вопрос о YouTrack здесь , но нет ответа в течение почти месяца.

У меня есть проект с несколькими модулями, в котором бэкэнд-часть Java не распознается как внутри корня проекта. Это связано с тем, что maven не имеет доступа к целевой папке для создания application.xml. Вот копия журнала IntelliJ .

Мой модуль TS / React выглядит нормально с завершением кода и т. Д., Но модули java backend и api вообще не распознаются. При наведении курсора на один из значков файла с красной буквой J отображается
«Java file outside of source root».

Пожалуйста, если есть какая-либо другая информация / журналы / что-нибудь, что я могу предоставить, пожалуйста, дайте мне знать.

IntelliJ IDEA 2021.1 (Ultimate Edition)
Build #IU-211.6693.111, built on April 6, 2021
Runtime version: 11.0.10+9-b1341.35 amd64
VM: Dynamic Code Evolution 64-Bit Server VM by JetBrains s.r.o.
Windows 10 10.0
GC: G1 Young Generation, G1 Old Generation
Memory: 2028M
Cores: 8
Non-Bundled Plugins: manjaro.mpb (1.5), izhangzhihao.rainbow.brackets (6.17)
Kotlin: 211-1.4.32-release-IJ6693.72

Дополнительно:  Капсулы корень кудзу kudzuvine root baihekang brand

If you do an ‘import from git’, IntelliJ doesn’t import the project structure from maven (or gradle) automatically.

One way to do this afterwards is to right-click on the pom.xml file in the root directory, and select ‘Add as maven project’. Then the folders will be marked correctly, and dependent libraries will be imported. There should be no need to mark individual source folders manually.

Click on «maven» on the right toolbar in IntelliJ and then click on the refresh button.

Java file outside of source root intellij idea что делать

** Error: (vlog-13069) ** while parsing file included at ./pcie_cpl_pkg.sv(9) ** at pcie_cpl_pins.sv(35): near “pcie_cpl_pins”: syntax.

[Solved]-Java file outside of source root intelliJ-Springboot

Describe the bug After updated to version 64.0.0 it started to show what i thinks is the default icon for what an icon is missing. When hovering the icon it shows a label with the text «Java file outside of source root»

Expected Behavior Show the correct Java icon for .java files.

Environment IntelliJ IDEA 2022.1 (Ultimate Edition) Build #IU-221.5080.210, built on April 11, 2022 Runtime version: 11.0.14.1+1-b2043.25 x86_64 VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o. macOS 12.3.1 GC: G1 Young Generation, G1 Old Generation Memory: 2048M Cores: 8 Registry: ide.intellij.laf.enable.animation=true ide.balloon.shadow.size=0 ide.images.show.chessboard=true

Non-Bundled Plugins: com.mallowigi.idea (17.0) com.github.copilot (1.1.17.1262) org.asciidoctor.intellij.asciidoc (0.37.17) org.sonarlint.idea (6.7.0.45926) mobi.hsz.idea.gitignore (4.4.0) com.mallowigi (64.0.0) dev.flikas.idea.spring.boot.assistant.plugin (0.2.4) intellij.prettierJS (221.5080.169) izhangzhihao.rainbow.brackets (6.22) io.jmix.studio (1.2.1-213) com.haulmont.jpab (2022.2.2-221)

Expected

stale commented on May 15, 2022

This PR has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

Typescript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

TensorFlow

An Open Source Machine Learning Framework for Everyone

Django

The Web framework for perfectionists with deadlines.

Laravel

A PHP framework for web artisans

Bring data to life with SVG, Canvas and HTML.

Recommend Topics

JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

Some thing interesting about web. New door for the world.

Server

A server is a program made to process requests and deliver data to clients.

Machine learning

Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

Visualization

Some thing interesting about visualization, use data art

Some thing interesting about game, make everyone happy.

Recommend Org

We are working to build community through open source technology. NB: members must have two-factor auth.

If you are trying to access a class and its member variables and methods in IntelliJ IDE for an external dependency (be it Maven or Gradle) you may see a tooltip saying «Cannot find declaration to go to» if the source of the class is not available.

If you hover over your class if you see «Java file outside of source root» and when you try to run the main method you would not be able to run the application with a message «Nothing here»

Open installed Plugins (press Shift key twice) and disable Gradle and restart IntelliJ, you will be prompted to enable Gradle, once dependencies and their source are downloaded and the build is complete, this error should be fixed.

report this ad

I have cloned a spring boot project from GitLab having multiple branches in IntelliJ. I checkout to the branch in which I want to work. But I am getting «Java file outside of source root» on all the files. Please suggest what I am doing wrong. I just installed IntelliJ and it’s the first project that I am importing.

27 Answers 27

[Solved]-Java file outside of source root intelliJ-Springboot

Very simple solution: —

[Solved]-Java file outside of source root intelliJ-Springboot

[Solved]-Java file outside of source root intelliJ-Springboot

Then click ‘OK’ — this then loads all the Maven dependencies from the unused pom file and, for me, everything was finally fixed!

Anwar Benhamada 191

Hate to add yet another method; but this one worked for me after trying and failing with the above methods. I had a multi-mode project. Unlinked all maven projects in Maven workspace and reloaded as maven project by clicking root poom.xml in project workspace. Not sure whether this will always work and for everyone.

[Solved]-Java file outside of source root intelliJ-Springboot

Quan Truong 124

I’m having a similar issue for an Android project in Android Studio Chipmunk 2021.2.1 Patch 1. It looks like a known bug related to using manifest.srcFile : https://issuetracker.google.com/issues/218370114?hl=ko

Apparently the options are switching to the canary channel or waiting for the fix to be released on the stable channel. Or getting rid of manifest.srcFile in your build.gradle .

In intellij: click Maven, select the project and right, select Unignore Projects

You can right click the POM.xml, select «Maven — Unignore projects».

Diego Virgüez 135

Оцените статью
Master Hi-technology
Добавить комментарий