Error could not get the current mvc module paths

I have a multi-module Java(Spring) project, which build by Gradle 6.7.1. And I use in Jetbrain IDEA to develop. The file Structure like this: root |--orm | +---hibernates | |--web |...

I have a multi-module Java(Spring) project, which build by Gradle 6.7.1. And I use in Jetbrain IDEA to develop. The file Structure like this:

root
  |--orm
  |   +---hibernates
  |
  |--web
      |--mvc
      |--rest

And then, I have tried some codes in my module project like below, what I get all are root path (/home/user/IdeaProjects/root/), not module path (/home/user/IdeaProjects/root/web/mvc). How can I get module path (/home/user/IdeaProjects/root/web/mvc) ?

new File("").getAbsolutePath()

asked Mar 25, 2021 at 8:33

Jessie Chen's user avatar

Jessie ChenJessie Chen

2,5261 gold badge24 silver badges31 bronze badges

3

Assuming for instance that your mvc project is setup like this in setting.gradle, in the root folder :

include 'mvc'
project(':mvc').projectDir = new File('./web/mvc')

Then, to get the path /home/user/IdeaProjects/root/web/mvc, just try this :

println project(':mvc').projectDir

Will prints :

/home/user/IdeaProjects/root/web/mvc

answered Mar 25, 2021 at 10:50

ToYonos's user avatar

ToYonosToYonos

16.2k2 gold badges54 silver badges70 bronze badges

based on the answer of @ToYonos. We can do that by this:

  1. settings.gradle gets the project path of every module.
  2. write a key value into the info.properties in every module.
  3. Spring Project read this properties file.

Code

Because struct of my project is:
root
  |--orm
  |   +---mybatis
  |   +---jpa
  |   +---...
  |--web
      +--mvc
      +--rest
      +--...

So, I should loop twice to get the module name. And I exclude project without build.gradle.

file("${rootDir}").eachDir {
    it.eachDirMatch(~/.*/) {
        if (it.list().contains("build.gradle")) {
            def moduleName = "${it.parentFile.name}:${it.name}"
            println "   ${moduleName}"
            include moduleName
}}}

And then, read and write info.properties.

import java.nio.file.Paths

// read
def project_dir = project(":${moduleName}").projectDir
def propFile = Paths.get("${project_dir}", "src", "main","resources","info.properties").toFile()
propFile.createNewFile()
Properties props = new Properties()
propFile.withInputStream {
    props.load(it)
}

// write
props.setProperty("project.dir","$project_dir")
props.store propFile.newWriter(), null

answered Mar 25, 2021 at 9:43

Jessie Chen's user avatar

Jessie ChenJessie Chen

2,5261 gold badge24 silver badges31 bronze badges

well, after suffering a few hours, I got a solution
I have used the ts-node package, and I got the same error Error: Cannot find module '@modules/logger'

You need to add ts-node configuration in the tsconfig.json file.
You can get more infor at ts-node

{
    "ts-node": {
        // Do not forget to `npm i -D tsconfig-paths`
        "require": ["tsconfig-paths/register"]
    },
    "compilerOptions": {
        "lib": ["es5", "es6", "es7"],
        "target": "es2017",
        "module": "commonjs",
        "moduleResolution": "node",
        "rootDir": "src",
        "outDir": "build",
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "esModuleInterop": true,
        "noImplicitAny": true,
        "strict": true,
        "resolveJsonModule": true,
        "allowJs": true,
        "sourceMap": true,

        "baseUrl": ".",
        "paths": {
            "@modules/*": ["src/modules/*"],
            "*": ["node_modules/*"]
        },

    },
    "include": ["src/**/*"]
}

  • Remove From My Forums
  • Question

  • User2080466204 posted

    Hello everyone,

    I have created a MVC module and now I must integrate it into a standard ASP website.

    I know this sounds pretty basic, but I really have no clue on how to do it.

    The module is in a *separate* visual studio project, with its configuration and all. I don’t mind putting it together with the main website, but it must be made with the least interference as possible. Ideally there would be no change in the main website,
    except the link to the MVC module.

    The MVC module lies on a directory of this website, and must:

    1. Use the master page of the website. If I try to simply link the pages to that master page, it throws an exception saying that the path cannot go lower than the base of the MVC project.
    2. Have the smallest impact on the website.

    Thank you for your help. I have no idea on how to begin this…

Answers

    • Marked as answer by

      Thursday, October 7, 2021 12:00 AM

В Python может быть несколько причин возникновения ошибки ModuleNotFoundError: No module named ...:

  • Модуль Python не установлен.
  • Есть конфликт в названиях пакета и модуля.
  • Есть конфликт зависимости модулей Python.

Рассмотрим варианты их решения.

Модуль не установлен

В первую очередь нужно проверить, установлен ли модуль. Для использования модуля в программе его нужно установить. Например, если попробовать использовать numpy без установки с помощью pip install будет следующая ошибка:

Traceback (most recent call last):
   File "", line 1, in 
 ModuleNotFoundError: No module named 'numpy'

Для установки нужного модуля используйте следующую команду:

pip install numpy
# или
pip3 install numpy

Или вот эту если используете Anaconda:

conda install numpy

Учтите, что может быть несколько экземпляров Python (или виртуальных сред) в системе. Модуль нужно устанавливать в определенный экземпляр.

Конфликт имен библиотеки и модуля

Еще одна причина ошибки No module named — конфликт в названиях пакета и модуля. Предположим, есть следующая структура проекта Python:

demo-project
 └───utils
         __init__.py
         string_utils.py
         utils.py

Если использовать следующую инструкцию импорта файла utils.py, то Python вернет ошибку ModuleNotFoundError.


>>> import utils.string_utils
Traceback (most recent call last):
File "C:demo-projectutilsutils.py", line 1, in
import utils.string_utils
ModuleNotFoundError: No module named 'utils.string_utils';
'utils' is not a package

В сообщении об ошибке сказано, что «utils is not a package». utils — это имя пакета, но это также и имя модуля. Это приводит к конфликту, когда имя модуля перекрывает имя пакета/библиотеки. Для его разрешения нужно переименовать файл utils.py.

Иногда может существовать конфликт модулей Python, который и приводит к ошибке No module named.

Следующее сообщение явно указывает, что _numpy_compat.py в библиотеке scipy пытается импортировать модуль numpy.testing.nosetester.

Traceback (most recent call last):
   File "C:demo-projectvenv
Libsite-packages
         scipy_lib_numpy_compat.py", line 10, in
     from numpy.testing.nosetester import import_nose
 ModuleNotFoundError: No module named 'numpy.testing.nosetester'

Ошибка ModuleNotFoundError возникает из-за того, что модуль numpy.testing.nosetester удален из библиотеки в версии 1.18. Для решения этой проблемы нужно обновить numpy и scipy до последних версий.

pip install numpy --upgrade
pip install scipy --upgrade 

Понравилась статья? Поделить с друзьями:
  • Error could not get primary adapter handle
  • Error could not get file size of file как исправить
  • Error could not get file size of file skyrim
  • Error could not fork child process there are no available terminals 1
  • Error could not fork child process resource temporarily unavailable 1