0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Maven】同じ階層、同じクラス名が存在するプロジェクトをpom.xmlの依存関係に追加すると…

Posted at

前提

プロジェクトの構成・クラスの内容は以下となっています。

プロジェクト一覧
demo/
├── src/
│   └── main/
│       └── java/
│       └── com/example/demo/
│          └── DemoApplication.java
└── pom.xml

test1/
├── src/
│   └── main/
│       └── java/
│       └── com/example/test/
│          └── UserConfig.java
└── pom.xml

test2/
├── src/
│   └── main/
│       └── java/
│       └── com/example/test/
│          └── UserConfig.java
└── pom.xml
DemoApplication.java
package com.example.demo;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.example.test.UserConfig;

@SpringBootApplication
public class DemoApplication {
	public static void main(String[] args) {
		String name = UserConfig.USER_NAME;
		System.out.println(name);
	}
}
UserConfig.java
package com.example.test;

/**
 * test1プロジェクトのUserConfig
 */
public class UserConfig {
	public static final String USER_NAME = "tanaka";
}
UserConfig.java
package com.example.test;

/**
 * test2プロジェクトのUserConfig
 */
public class UserConfig {
	public static final String USER_NAME = "satou";
}
demo/pom.xml
    <dependency>
        <groupId>com.example</groupId>
        <artifactId>test1</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </dependency>
    <dependency>
        <groupId>com.example</groupId>
        <artifactId>test2</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </dependency>

結果

同じ階層、同じクラス名が存在するプロジェクトをpom.xmlの依存関係に追加し、そのクラスを使用すると先に依存関係を追加したクラスが優先されて使用されます。
image.png

依存関係を逆にして確認すると、"satou"が出力されます。

demo/pom.xml
    <dependency>
        <groupId>com.example</groupId>
        <artifactId>test2</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </dependency>
    <dependency>
        <groupId>com.example</groupId>
        <artifactId>test1</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </dependency>

image.png

基本的に同じ階層、同じクラス名にすることはNGですが、場合によっては使いどころがあります。
※例えば、依存関係にパッケージ標準クラスに対して機能を追加したい場合など...

何かの参考になれば...

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?