├── .github
└── workflows
│ ├── codeql-analysis.yml
│ └── maven.yml
├── .gitignore
├── CHANGELOG.md
├── LICENSE
├── README.md
├── dependency-upgrade-rules.xml
├── docs
├── schema-context-cross-modules.jpg
├── schema-context-cross-modules.tif
├── schema-context-within-modules.jpg
└── schema-context-within-modules.tif
├── integration-tests-spring-boot
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ ├── io
│ │ └── github
│ │ │ └── tomdw
│ │ │ └── java
│ │ │ └── modules
│ │ │ └── spring
│ │ │ └── boot
│ │ │ └── starter
│ │ │ └── tests
│ │ │ ├── DummyTestBean.java
│ │ │ └── SpringBootTestApplication.java
│ │ └── module-info.java
│ └── test
│ └── java
│ └── io
│ └── github
│ └── tomdw
│ └── java
│ └── modules
│ └── spring
│ └── boot
│ └── starter
│ └── tests
│ └── JavaModulesContextBootStarterTest.java
├── integration-tests
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ ├── io
│ │ └── github
│ │ │ └── tomdw
│ │ │ └── java
│ │ │ └── modules
│ │ │ └── spring
│ │ │ └── integration
│ │ │ └── tests
│ │ │ ├── IntegrationTestConfiguration.java
│ │ │ ├── IntegrationTestService.java
│ │ │ └── IntegrationTestUsingConstructorInjectionService.java
│ │ └── module-info.java
│ └── test
│ └── java
│ └── io
│ └── github
│ └── tomdw
│ └── java
│ └── modules
│ └── spring
│ └── integration
│ └── tests
│ └── JavaModulesSpringContextBootIntegrationTest.java
├── java-modules-context-boot-starter
├── pom.xml
└── src
│ └── main
│ ├── java
│ ├── io
│ │ └── github
│ │ │ └── tomdw
│ │ │ └── java
│ │ │ └── modules
│ │ │ └── context
│ │ │ └── boot
│ │ │ └── starter
│ │ │ └── JavaModulesContextBootApplicationContextInitializer.java
│ └── module-info.java
│ └── resources
│ └── META-INF
│ └── spring.factories
├── java-modules-context-boot
├── pom.xml
└── src
│ └── main
│ └── java
│ ├── io
│ └── github
│ │ └── tomdw
│ │ └── java
│ │ └── modules
│ │ └── context
│ │ └── boot
│ │ ├── api
│ │ ├── ModuleContext.java
│ │ ├── ModuleContextBooter.java
│ │ ├── ModuleServiceProvider.java
│ │ └── ModuleServiceReference.java
│ │ └── internal
│ │ ├── ApplicationContextInstantiationException.java
│ │ ├── InactiveDefaultApplicationContextException.java
│ │ ├── LazyRetrieveBeanFromContextStrategy.java
│ │ ├── LazyRetrieveBeanFromContextWithServiceNameStrategy.java
│ │ ├── LazyRetrieveBeanFromContextWithoutServiceNameStrategy.java
│ │ ├── ModuleContextRegistry.java
│ │ ├── ModuleServiceReferenceAnnotationPostProcessor.java
│ │ └── ModuleServiceReferenceElement.java
│ └── module-info.java
├── pom.xml
└── samples
├── basicapplication
├── application
│ ├── pom.xml
│ └── src
│ │ └── main
│ │ └── java
│ │ ├── io
│ │ └── github
│ │ │ └── tomdw
│ │ │ └── java
│ │ │ └── modules
│ │ │ └── spring
│ │ │ └── samples
│ │ │ └── basicapplication
│ │ │ └── internal
│ │ │ ├── MainApplicationConfiguration.java
│ │ │ └── MessageGenerator.java
│ │ └── module-info.java
├── pom.xml
└── speaker
│ ├── pom.xml
│ └── src
│ ├── main
│ └── java
│ │ ├── io
│ │ └── github
│ │ │ └── tomdw
│ │ │ └── java
│ │ │ └── modules
│ │ │ └── spring
│ │ │ └── samples
│ │ │ └── basicapplication
│ │ │ └── speaker
│ │ │ ├── api
│ │ │ ├── FailingSpeakerService.java
│ │ │ ├── MultipleSpeakerService.java
│ │ │ ├── MultipleSpeakerWithGenericsService.java
│ │ │ ├── NamedSpeakerService.java
│ │ │ ├── NoSpeakerCheckedException.java
│ │ │ ├── NoSpeakerRuntimeException.java
│ │ │ └── SpeakerService.java
│ │ │ └── internal
│ │ │ ├── DefaultFailingSpeakerService.java
│ │ │ ├── DefaultMultipleSpeakerService.java
│ │ │ ├── DefaultMultipleSpeakerWithGenericsService.java
│ │ │ ├── DefaultNamedSpeakerService.java
│ │ │ ├── DefaultSpeakerService.java
│ │ │ ├── MultipleSpeakerWithGenericsServiceProvider.java
│ │ │ ├── NamedSpeakerServiceProvider.java
│ │ │ ├── OtherMultipleSpeakerService.java
│ │ │ ├── OtherNamedSpeakerService.java
│ │ │ └── SpeakerConfiguration.java
│ │ └── module-info.java
│ └── test
│ └── java
│ └── io
│ └── github
│ └── tomdw
│ └── java
│ └── modules
│ └── spring
│ └── samples
│ └── basicapplication
│ └── speaker
│ └── internal
│ └── DefaultSpeakerServiceTest.java
└── pom.xml
/.github/workflows/codeql-analysis.yml:
--------------------------------------------------------------------------------
1 | # For most projects, this workflow file will not need changing; you simply need
2 | # to commit it to your repository.
3 | #
4 | # You may wish to alter this file to override the set of languages analyzed,
5 | # or to provide custom queries or build logic.
6 | #
7 | # ******** NOTE ********
8 | # We have attempted to detect the languages in your repository. Please check
9 | # the `language` matrix defined below to confirm you have the correct set of
10 | # supported CodeQL languages.
11 | # ******** NOTE ********
12 |
13 | name: "CodeQL"
14 |
15 | on:
16 | push:
17 | branches: [ master ]
18 | pull_request:
19 | # The branches below must be a subset of the branches above
20 | branches: [ master ]
21 | schedule:
22 | - cron: '27 5 * * 0'
23 |
24 | jobs:
25 | analyze:
26 | name: Analyze
27 | runs-on: ubuntu-latest
28 |
29 | strategy:
30 | fail-fast: false
31 | matrix:
32 | language: [ 'java' ]
33 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ]
34 | # Learn more...
35 | # https://docs.github.com/en/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#overriding-automatic-language-detection
36 |
37 | steps:
38 | - name: Checkout repository
39 | uses: actions/checkout@v2
40 |
41 | # Initializes the CodeQL tools for scanning.
42 | - name: Initialize CodeQL
43 | uses: github/codeql-action/init@v1
44 | with:
45 | languages: ${{ matrix.language }}
46 | # If you wish to specify custom queries, you can do so here or in a config file.
47 | # By default, queries listed here will override any specified in a config file.
48 | # Prefix the list here with "+" to use these queries and those in the config file.
49 | # queries: ./path/to/local/query, your-org/your-repo/queries@main
50 |
51 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
52 | # If this step fails, then you should remove it and run the build manually (see below)
53 | - name: Autobuild
54 | uses: github/codeql-action/autobuild@v1
55 |
56 | # ℹ️ Command-line programs to run using the OS shell.
57 | # 📚 https://git.io/JvXDl
58 |
59 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
60 | # and modify them (or add more) to build your code if your project
61 | # uses a compiled language
62 |
63 | #- run: |
64 | # make bootstrap
65 | # make release
66 |
67 | - name: Perform CodeQL Analysis
68 | uses: github/codeql-action/analyze@v1
69 |
--------------------------------------------------------------------------------
/.github/workflows/maven.yml:
--------------------------------------------------------------------------------
1 | # This workflow will build a Java project with Maven
2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven
3 |
4 | name: Java CI with Maven
5 |
6 | on:
7 | push:
8 | branches: [ master ]
9 | pull_request:
10 | branches: [ master ]
11 |
12 | jobs:
13 | build:
14 |
15 | runs-on: ubuntu-latest
16 |
17 | steps:
18 | - uses: actions/checkout@v2
19 | - name: Set up JDK 11
20 | uses: actions/setup-java@v1
21 | with:
22 | java-version: 11
23 | - name: Build with Maven
24 | run: mvn -B package --file pom.xml
25 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Manually added
2 | target/
3 |
4 | # Created by https://www.gitignore.io/api/git,java,linux,macos,eclipse,windows,intellij
5 |
6 | ### Eclipse ###
7 |
8 | .metadata
9 | bin/
10 | tmp/
11 | *.tmp
12 | *.bak
13 | *.swp
14 | *~.nib
15 | local.properties
16 | .settings/
17 | .loadpath
18 | .recommenders
19 |
20 | # External tool builders
21 | .externalToolBuilders/
22 |
23 | # Locally stored "Eclipse launch configurations"
24 | *.launch
25 |
26 | # PyDev specific (Python IDE for Eclipse)
27 | *.pydevproject
28 |
29 | # CDT-specific (C/C++ Development Tooling)
30 | .cproject
31 |
32 | # Java annotation processor (APT)
33 | .factorypath
34 |
35 | # PDT-specific (PHP Development Tools)
36 | .buildpath
37 |
38 | # sbteclipse plugin
39 | .target
40 |
41 | # Tern plugin
42 | .tern-project
43 |
44 | # TeXlipse plugin
45 | .texlipse
46 |
47 | # STS (Spring Tool Suite)
48 | .springBeans
49 |
50 | # Code Recommenders
51 | .recommenders/
52 |
53 | # Scala IDE specific (Scala & Java development for Eclipse)
54 | .cache-main
55 | .scala_dependencies
56 | .worksheet
57 |
58 | ### Eclipse Patch ###
59 | # Eclipse Core
60 | .project
61 |
62 | # JDT-specific (Eclipse Java Development Tools)
63 | .classpath
64 |
65 | ### Git ###
66 | *.orig
67 |
68 | ### Intellij ###
69 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
70 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
71 |
72 | # User-specific stuff:
73 | .idea/**/workspace.xml
74 | .idea/**/tasks.xml
75 | .idea/dictionaries
76 |
77 | # Sensitive or high-churn files:
78 | .idea/**/dataSources/
79 | .idea/**/dataSources.ids
80 | .idea/**/dataSources.xml
81 | .idea/**/dataSources.local.xml
82 | .idea/**/sqlDataSources.xml
83 | .idea/**/dynamic.xml
84 | .idea/**/uiDesigner.xml
85 |
86 | # Gradle:
87 | .idea/**/gradle.xml
88 | .idea/**/libraries
89 |
90 | # CMake
91 | cmake-build-debug/
92 |
93 | # Mongo Explorer plugin:
94 | .idea/**/mongoSettings.xml
95 |
96 | ## File-based project format:
97 | *.iws
98 |
99 | ## Plugin-specific files:
100 |
101 | # IntelliJ
102 | /out/
103 |
104 | # mpeltonen/sbt-idea plugin
105 | .idea_modules/
106 |
107 | # JIRA plugin
108 | atlassian-ide-plugin.xml
109 |
110 | # Cursive Clojure plugin
111 | .idea/replstate.xml
112 |
113 | # Ruby plugin and RubyMine
114 | /.rakeTasks
115 |
116 | # Crashlytics plugin (for Android Studio and IntelliJ)
117 | com_crashlytics_export_strings.xml
118 | crashlytics.properties
119 | crashlytics-build.properties
120 | fabric.properties
121 |
122 | ### Intellij Patch ###
123 | # Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721
124 |
125 | # *.iml
126 | # modules.xml
127 | # .idea/misc.xml
128 | # *.ipr
129 |
130 | # Sonarlint plugin
131 | .idea/sonarlint
132 |
133 | ### Java ###
134 | # Compiled class file
135 | *.class
136 |
137 | # Log file
138 | *.log
139 |
140 | # BlueJ files
141 | *.ctxt
142 |
143 | # Mobile Tools for Java (J2ME)
144 | .mtj.tmp/
145 |
146 | # Package Files #
147 | *.jar
148 | *.war
149 | *.ear
150 | *.zip
151 | *.tar.gz
152 | *.rar
153 |
154 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
155 | hs_err_pid*
156 |
157 | ### Linux ###
158 | *~
159 |
160 | # temporary files which can be created if a process still has a handle open of a deleted file
161 | .fuse_hidden*
162 |
163 | # KDE directory preferences
164 | .directory
165 |
166 | # Linux trash folder which might appear on any partition or disk
167 | .Trash-*
168 |
169 | # .nfs files are created when an open file is removed but is still being accessed
170 | .nfs*
171 |
172 | ### macOS ###
173 | *.DS_Store
174 | .AppleDouble
175 | .LSOverride
176 |
177 | # Icon must end with two \r
178 | Icon
179 |
180 | # Thumbnails
181 | ._*
182 |
183 | # Files that might appear in the root of a volume
184 | .DocumentRevisions-V100
185 | .fseventsd
186 | .Spotlight-V100
187 | .TemporaryItems
188 | .Trashes
189 | .VolumeIcon.icns
190 | .com.apple.timemachine.donotpresent
191 |
192 | # Directories potentially created on remote AFP share
193 | .AppleDB
194 | .AppleDesktop
195 | Network Trash Folder
196 | Temporary Items
197 | .apdisk
198 |
199 | ### Windows ###
200 | # Windows thumbnail cache files
201 | Thumbs.db
202 | ehthumbs.db
203 | ehthumbs_vista.db
204 |
205 | # Folder config file
206 | Desktop.ini
207 |
208 | # Recycle Bin used on file shares
209 | $RECYCLE.BIN/
210 |
211 | # Windows Installer files
212 | *.cab
213 | *.msi
214 | *.msm
215 | *.msp
216 |
217 | # Windows shortcuts
218 | *.lnk
219 |
220 | # End of https://www.gitignore.io/api/git,java,linux,macos,eclipse,windows,intellij
221 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # 0.0.6
2 | ## Dependencies
3 | - Update Spring to 5.3.23
4 | - Update Spring boot to 2.7.3
5 | - Update Junit to 5.9.0
6 | - Update AssertJ to 3.23.1
7 |
8 | # 0.0.5
9 | ## Features
10 | - Introduce Spring Boot Starter to enable standard spring boot application complemented with more isolated modules with their own spring context
11 | - Make Spring Boot starter act as an ApplicationContextInitializer to get Module Contexts booted as early as possible.
12 | - Introduce default application context to retrieve beans from when the Module has no @ModuleContext.
13 | - Spring Boot starter sets the main spring boot context as default application context (e.g. enables using ModuleServiceProvider from spring boot context modules).
14 | - Set Application Context Id to include the java module name. Allows usefull visualisation in e.g. IntelliJ spring support.
15 | - Also support @ModuleServiceReference in the default application context (i.e. which is the main spring boot application context when used with the spring boot starter)
16 | - Support using @ModuleServiceReference on constructor parameters for constructor injection of services loaded from other module contexts
17 | - The Environment of the default spring context is now shared with all other context. This allows other contexts to also read spring properties.
18 | - An exception is thrown when trying to load a bean from the default application context before it is active
19 |
20 | ## Bugfix
21 | - Remove workaround for jdk bug https://bugs.openjdk.java.net/browse/JDK-8241770. Minimum jdk 11.0.11 is required from now on.
22 | - Some logging statements logged the wrong Module name for which services where retrieved
23 | - Make sure registering a new application context for the same module is not possible
24 | - Make sure triggering ModuleContextBooter.boot multiple times does not register application contexts multiple times
25 | - Make sure using ModuleServiceProvider.provide is possible before an explicit ModuleContextBooter.boot without multiple application contexts as result
26 | - Get rid of the INFO log statement for the ModuleServiceReferenceAnnotationPostProcessorConfiguration not being eligible for post processing
27 |
28 | ## Dependencies
29 | - Update Spring to 5.3.17
30 | - Update Spring boot to 2.6.4
31 | - Update Junit to 5.8.2
32 | - Update AssertJ to 3.22.0
33 | - Update jakarta inject-api to 1.0.5
34 |
35 | # 0.0.3
36 | - Implement workaround for JDK bug https://bugs.openjdk.java.net/browse/JDK-8241770
37 | - Upgrade spring version
38 | - Upgrade test dependencies
39 | - Centralise dependency management in poms
40 | - Use java-modules-parent 0.0.3
41 |
42 | # 0.0.2
43 | - Upgrade spring version
44 | - Support for generics in an object inside a list
45 | - less logging by logging retrieval of beans on debug level
46 | - add ability to selectively provide a bean or service based on the bean name when multiple beans of the same type are present in an application context
47 |
48 | # 0.0.1
49 | - Initial Version
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # java-modules-context-boot
2 | Simple framework to boot a spring context within each java module
3 |
4 | 1. [Requirements](#requirements)
5 | 2. [Maven Dependency](#maven-dependency)
6 | 3. [Define a spring context within a module](#define-a-spring-context-within-a-module)
7 | 4. [Starting the application](#starting-the-application)
8 | 5. [Integrating modules using services](#integrating-modules-using-services)
9 | 6. [Samples](#samples)
10 |
11 | The [Boot Spring Context within each Java 11 Module](https://devcreativity.wordpress.com/2017/11/18/boot-spring-context-within-each-java-9-module/) blog post describes the approach in detail.
12 |
13 | ## Requirements
14 |
15 | - uses Spring as automatic modules or spring boot with the starter
16 | - build and run using jdk11 on the modulepath
17 | - Use jdk 11.0.11 or higher because of bug in jdk in earlier versions https://bugs.openjdk.java.net/browse/JDK-8241770.
18 |
19 | ## Maven Dependency
20 |
21 | The dependency to use is
22 |
23 | ```xml
24 |
25 | io.github.tomdw.java.modules.spring
26 | java-modules-context-boot
27 | 0.0.6
28 |
29 | ```
30 |
31 | which provides you with a java module named
32 |
33 | `io.github.tomdw.java.modules.context.boot`
34 |
35 | transitively providing read access to spring modules and jakarta's java.inject (still in javax.inject package).
36 |
37 | ## Define a spring context within a module
38 |
39 | To define a spring context within a java module, you need to:
40 | - use the ModuleContext annotation on the module pointing to a java-based spring configuration
41 | - require io.github.tomdw.java.modules.context.boot
42 | - open the package of the module to spring
43 |
44 | For example:
45 |
46 | ```
47 | @ModuleContext(
48 | mainConfigurationClass = SpeakerConfiguration.class
49 | )
50 | module io.github.tomdw.java.modules.spring.samples.basicapplication.speaker {
51 | requires io.github.tomdw.java.modules.context.boot;
52 | opens io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.internal to spring.beans, spring.core, spring.context;
53 | }
54 | ```
55 |
56 | java-modules-context-boot will make sure to start a separate spring context for every module annotated with this annotation.
57 |
58 | If you would like to use another `ApplicationContext` than the default `AnnotationConfigApplicationContext` you can specify the class using the `applicationContextClass` parameter of the `@ModuleContext` annotation. This class should extend `GenericApplicationContext` and implement the `AnnotationConfigRegistry` interface.
59 |
60 | This could be useful when you want to use a Spring Boot specific ApplicationContext that contains starters. For example an application context supporting web servlets such as `org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext`.
61 |
62 | ## Starting the application
63 |
64 | ### Using the built-in main class
65 |
66 | You can use the ModuleContextBooter.main as main method to start the application.
67 |
68 | Make sure to add the application modules to your module path. For every module on the module path annotated with @ModuleContext
69 | we boot a spring context.
70 |
71 | ### Using your own (main) classes
72 |
73 | When you want to control when the modules get booted with spring contexts you can call
74 |
75 | ```
76 | ModuleContextBooter.boot();
77 | ```
78 | from anywhere in your project's code.
79 |
80 | ### Using the Spring Boot Starter
81 |
82 | The dependency to use is
83 |
84 | ```xml
85 |
86 | io.github.tomdw.java.modules.spring
87 | java-modules-context-boot-starter
88 | 0.0.6
89 |
90 | ```
91 |
92 | which provides you with a java module named
93 |
94 | `be.aca.platform.java.modules.context.boot.starter`
95 |
96 | and which is a standard Spring Boot starter that automatically triggers `ModuleContextBooter.boot(springBootApplicationContext)`.
97 | The framework uses the given `springBootApplicationContext` as default application context when retrieving beans for a Module.
98 |
99 | This alternative enables applications that are standard spring boot applications running on the modulepath to easily integrate other modules which define their own ModuleContext for better isolation.
100 |
101 |
102 | ## Integrating modules using services
103 |
104 | Using services through the ServiceLoader API allows to integrate modules in a loosely coupled way. The
105 | following sections describe how to do this between multiple spring contexts in different modules.
106 |
107 | ### Provide a module service from the spring context
108 |
109 | To provide a service through the ServiceLoader API you need to add the 'provides' in your module-info:
110 | ```
111 | @ModuleContext(...)
112 | module io.github.tomdw.java.modules.spring.samples.basicapplication.speaker {
113 | ...
114 | provides SpeakerService with DefaultSpeakerService;
115 | ...
116 | }
117 | ```
118 |
119 | Instead of using a default contructor, leverage the 'provider' factory method alternative as follows:
120 | ```
121 | @Named
122 | public class DefaultSpeakerService implements SpeakerService {
123 | ...
124 | public static SpeakerService provider() {
125 | return ModuleServiceProvider.provide(SpeakerService.class);
126 | }
127 | ...
128 | }
129 |
130 | ```
131 |
132 | Best practice is to provide the service with the interface class.
133 | This way a dynamic proxy is created for consumers. It prevents exceptions while providing instances of beans while certain springContexts are still inactive.
134 | The actual bean lookup will be performed when this service is invoked.
135 |
136 | If you have 2 services of the same type (for instance a datasource), you can provide the proper service using the bean name as follows:
137 | ```
138 | public class SpeakerServiceProvider {
139 |
140 | public static SpeakerService provider() {
141 | return ModuleServiceProvider.provide(SpeakerService.class, "speaker-service-bean-name");
142 | }
143 |
144 | private SpeakerServiceProvider() {
145 | //must not be constructed
146 | }
147 | }
148 | ```
149 |
150 | The ModuleServiceProvider.provide helper method retrieves a bean of the given type from
151 | the spring application context associated with the module calling the provide method.
152 |
153 | ### Reference a module service from another spring context
154 |
155 | Using a service in another module can simply be done by annotating with @ModuleServiceReference:
156 | ```
157 | @Named
158 | public class MessageGenerator {
159 |
160 | @ModuleServiceReference
161 | private SpeakerService speakerService;
162 |
163 | }
164 |
165 | ```
166 |
167 | Don't forget to add a 'uses' entry in the module-info:
168 | ```
169 | @ModuleContext(...)
170 | module io.github.tomdw.java.modules.spring.samples.basicapplication.application {
171 | ...
172 | uses SpeakerService;
173 | }
174 | ```
175 |
176 | Every spring context is enriched with a processor to retrieve the necessary services
177 | through the ServiceLoader API and make them available for injection in the spring context of that module.
178 |
179 | ### Reference a list of module services from another spring context
180 |
181 | Similar to using a single service, the annotation @ModuleServiceReference can be used to inject a list of all services that implement a certain interface.
182 | ```
183 | @Named
184 | public class MessageGenerator {
185 |
186 | @ModuleServiceReference
187 | @Named("speakerServiceList")
188 | private List speakerService;
189 |
190 | }
191 |
192 | ```
193 |
194 | The difference is that we cannot inject by type, because of generics limitations a list of speakerServices are not known by spring to inject.
195 | To support this, we are registring the list of provided services with a bean name. By convention this name will be the type of the services suffixed by "List".
196 | When injecting the service list you should use the @Named or @Qualifier annotation to specify the name following this naming convention.
197 |
198 | ### Sharing Spring Environment
199 | When a default application context is provided, it's Environment will be shared with all other contexts. This allows all contexts to share configuration, including configuration set in tests.
200 |
201 | ### Using in combination with @DirtiesContext
202 | When using this framework in combination wtih DirtiesContext, the registry should be reset whenever the spring context is refreshed. Call `ModuleContextBooter.reset()` whenever the context is refreshed (e.g. in @AfterAll when DirtiesContext runs after each class).
203 |
204 | ## Samples
205 | - Under 'samples' the 'basicapplication' sample shows this in a working hello world application.
206 | - follow the instructions regarding the java toolchains from the [java-modules-parent project](https://github.com/tomdw/java-modules-parent)
207 | - start the application using 'mvn toolchains:toolchain exec:exec' from within the 'basicapplication/application' module.
208 |
--------------------------------------------------------------------------------
/dependency-upgrade-rules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | (?i).*Alpha(?:-?\d+)?
6 | (?i).*a(?:-?\d+)?
7 | (?i).*Beta(?:-?\d+)?
8 | (?i).*-B(?:-?\d+)?
9 | (?i).*RC(?:-?\d+)?
10 | (?i).*CR(?:-?\d+)?
11 | (?i).*M(?:-?\d+)?
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/docs/schema-context-cross-modules.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tomdw/java-modules-context-boot/c7a40523f5e8e983e7dd52e82c5cc6a746b3d0d0/docs/schema-context-cross-modules.jpg
--------------------------------------------------------------------------------
/docs/schema-context-cross-modules.tif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tomdw/java-modules-context-boot/c7a40523f5e8e983e7dd52e82c5cc6a746b3d0d0/docs/schema-context-cross-modules.tif
--------------------------------------------------------------------------------
/docs/schema-context-within-modules.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tomdw/java-modules-context-boot/c7a40523f5e8e983e7dd52e82c5cc6a746b3d0d0/docs/schema-context-within-modules.jpg
--------------------------------------------------------------------------------
/docs/schema-context-within-modules.tif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tomdw/java-modules-context-boot/c7a40523f5e8e983e7dd52e82c5cc6a746b3d0d0/docs/schema-context-within-modules.tif
--------------------------------------------------------------------------------
/integration-tests-spring-boot/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | java-modules-context-boot-build
5 | io.github.tomdw.java.modules.spring
6 | 0.0.7-SNAPSHOT
7 |
8 | 4.0.0
9 |
10 | integration-tests-spring-boot
11 |
12 |
13 |
14 | io.github.tomdw.java.modules.spring
15 | java-modules-context-boot-starter
16 |
17 |
18 | org.springframework.boot
19 | spring-boot-starter
20 |
21 |
22 | org.springframework.boot
23 | spring-boot-starter-test
24 | test
25 |
26 |
27 | io.github.tomdw.java.modules.spring.samples.basicapplication
28 | application
29 |
30 |
31 |
32 |
33 |
34 |
35 | org.codehaus.mojo
36 | build-helper-maven-plugin
37 | 3.1.0
38 |
39 |
40 | add-test-source
41 | generate-test-sources
42 |
43 | add-test-source
44 |
45 |
46 |
47 | src/main/java/io/github/tomdw/java/modules/spring/boot/starter/tests
48 |
49 |
50 |
51 |
52 | add-test-resource
53 | generate-test-resources
54 |
55 | add-test-resource
56 |
57 |
58 |
59 |
60 | src/main/resources
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
--------------------------------------------------------------------------------
/integration-tests-spring-boot/src/main/java/io/github/tomdw/java/modules/spring/boot/starter/tests/DummyTestBean.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.spring.boot.starter.tests;
2 |
3 | import org.springframework.stereotype.Component;
4 |
5 | import io.github.tomdw.java.modules.context.boot.api.ModuleServiceReference;
6 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService;
7 |
8 | @Component
9 | public class DummyTestBean {
10 |
11 | @ModuleServiceReference
12 | private SpeakerService speakerService;
13 |
14 | public SpeakerService getSpeakerService() {
15 | return speakerService;
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/integration-tests-spring-boot/src/main/java/io/github/tomdw/java/modules/spring/boot/starter/tests/SpringBootTestApplication.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.spring.boot.starter.tests;
2 |
3 | import org.springframework.boot.autoconfigure.SpringBootApplication;
4 |
5 | @SpringBootApplication
6 | public class SpringBootTestApplication {
7 | }
8 |
--------------------------------------------------------------------------------
/integration-tests-spring-boot/src/main/java/module-info.java:
--------------------------------------------------------------------------------
1 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService;
2 |
3 | open module io.github.tomdw.java.modules.spring.integration.tests.spring.boot {
4 | requires spring.boot.autoconfigure;
5 | requires spring.context;
6 |
7 | requires io.github.tomdw.java.modules.context.boot.starter;
8 | requires io.github.tomdw.java.modules.context.boot;
9 |
10 | requires io.github.tomdw.java.modules.spring.samples.basicapplication.application;
11 | requires io.github.tomdw.java.modules.spring.samples.basicapplication.speaker;
12 |
13 | uses SpeakerService;
14 | }
--------------------------------------------------------------------------------
/integration-tests-spring-boot/src/test/java/io/github/tomdw/java/modules/spring/boot/starter/tests/JavaModulesContextBootStarterTest.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.spring.boot.starter.tests;
2 |
3 | import static org.assertj.core.api.Assertions.assertThat;
4 |
5 | import java.util.List;
6 | import java.util.stream.Collectors;
7 |
8 | import org.junit.jupiter.api.Test;
9 | import org.springframework.beans.factory.annotation.Autowired;
10 | import org.springframework.boot.test.context.SpringBootTest;
11 | import org.springframework.context.ApplicationContext;
12 | import org.springframework.context.support.GenericApplicationContext;
13 |
14 | import io.github.tomdw.java.modules.context.boot.api.ModuleContextBooter;
15 | import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider;
16 |
17 | @SpringBootTest(classes = SpringBootTestApplication.class)
18 | public class JavaModulesContextBootStarterTest {
19 |
20 | @Autowired
21 | private ApplicationContext applicationContext;
22 |
23 | @Test
24 | public void springBootApplicationContextIsStartedAndDetectsOwnBeans() {
25 | assertThat(applicationContext).isNotNull();
26 | assertThat(applicationContext.getBean(DummyTestBean.class)).isNotNull();
27 | }
28 |
29 | @Test
30 | public void springBootStarterAutoConfiguresSpringApplicationContextForEveryModuleWithModuleContextAnnotation() {
31 | String[] expectedModuleNames = {"io.github.tomdw.java.modules.spring.samples.basicapplication.application",
32 | "io.github.tomdw.java.modules.spring.samples.basicapplication.speaker"};
33 | List modulesWithModuleContextAnnotation = ModuleLayer.boot().modules().stream().filter(module -> List.of(expectedModuleNames).contains(module.getName())).collect(Collectors.toList());
34 |
35 | assertThat(modulesWithModuleContextAnnotation.stream().map(Module::getName)).containsExactlyInAnyOrder(expectedModuleNames);
36 |
37 | modulesWithModuleContextAnnotation.forEach(
38 | module -> {
39 | GenericApplicationContext context = ModuleContextBooter.getContextFor(module);
40 | assertThat(context).withFailMessage("A context should have been created for module " + module.getName()).isNotNull();
41 | assertThat(context.isActive()).withFailMessage("The context should be active for module " + module.getName()).isTrue();
42 | }
43 | );
44 | }
45 |
46 | @Test
47 | public void moduleServiceProviderLooksForBeansInMainSpringBootContextWhenCallingModuleHasNoModuleContextAnnotation() {
48 | DummyTestBean providedBean = ModuleServiceProvider.provide(DummyTestBean.class);
49 | assertThat(providedBean).isNotNull();
50 |
51 | GenericApplicationContext contextForMainSpringBootModules = ModuleContextBooter.getContextFor(DummyTestBean.class.getModule());
52 | assertThat(contextForMainSpringBootModules).isSameAs(applicationContext);
53 | }
54 |
55 | @Test
56 | public void moduleServiceReferenceAnnotationAlsoInjectsServicesLoadedFromOtherModulesInMainSpringBootContext() {
57 | DummyTestBean dummyTestBean = applicationContext.getBean(DummyTestBean.class);
58 | assertThat(dummyTestBean).isNotNull();
59 | assertThat(dummyTestBean.getSpeakerService()).isNotNull();
60 | }
61 |
62 |
63 | }
64 |
--------------------------------------------------------------------------------
/integration-tests/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | java-modules-context-boot-build
5 | io.github.tomdw.java.modules.spring
6 | 0.0.7-SNAPSHOT
7 |
8 | 4.0.0
9 |
10 | io.github.tomdw.java.modules.spring
11 | integration-tests
12 |
13 |
14 |
15 | io.github.tomdw.java.modules.spring.samples.basicapplication
16 | application
17 |
18 |
19 | io.github.tomdw.java.modules.spring
20 | java-modules-context-boot
21 |
22 |
23 | org.springframework
24 | spring-beans
25 |
26 |
27 | org.springframework
28 | spring-context
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/integration-tests/src/main/java/io/github/tomdw/java/modules/spring/integration/tests/IntegrationTestConfiguration.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.spring.integration.tests;
2 |
3 | import org.springframework.context.annotation.Configuration;
4 | import org.springframework.context.annotation.Import;
5 |
6 | @Configuration
7 | @Import(value = {IntegrationTestUsingConstructorInjectionService.class, IntegrationTestService.class})
8 | public class IntegrationTestConfiguration {
9 |
10 | }
11 |
--------------------------------------------------------------------------------
/integration-tests/src/main/java/io/github/tomdw/java/modules/spring/integration/tests/IntegrationTestService.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.spring.integration.tests;
2 |
3 | import java.util.List;
4 |
5 | import javax.inject.Named;
6 |
7 | import org.springframework.beans.BeansException;
8 | import org.springframework.context.ApplicationContext;
9 | import org.springframework.context.ApplicationContextAware;
10 |
11 | import io.github.tomdw.java.modules.context.boot.api.ModuleServiceReference;
12 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService;
13 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerWithGenericsService;
14 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NamedSpeakerService;
15 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService;
16 |
17 | @Named
18 | public class IntegrationTestService implements ApplicationContextAware {
19 |
20 | @ModuleServiceReference
21 | private SpeakerService speakerService;
22 |
23 | @ModuleServiceReference
24 | @Named("multipleSpeakerServiceList")
25 | private List multipleSpeakerServices;
26 |
27 | @ModuleServiceReference
28 | private NamedSpeakerService namedSpeakerService;
29 |
30 | @ModuleServiceReference
31 | @Named("multipleSpeakerWithGenericsServiceList")
32 | private List> multipleSpeakerWithGenericsServices;
33 |
34 | private static ApplicationContext applicationContext;
35 |
36 | public List getMultipleSpeakerServices() {
37 | return multipleSpeakerServices;
38 | }
39 |
40 | public NamedSpeakerService getNamedSpeakerService() {
41 | return namedSpeakerService;
42 | }
43 |
44 | public List> getMultipleSpeakerWithGenericsServices() { return multipleSpeakerWithGenericsServices; }
45 |
46 | public SpeakerService getSpeakerService() {
47 | return speakerService;
48 | }
49 |
50 | public static ApplicationContext getApplicationContext() {
51 | return applicationContext;
52 | }
53 |
54 | @Override
55 | public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
56 | this.applicationContext = applicationContext;
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/integration-tests/src/main/java/io/github/tomdw/java/modules/spring/integration/tests/IntegrationTestUsingConstructorInjectionService.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.spring.integration.tests;
2 |
3 | import java.util.List;
4 |
5 | import javax.inject.Named;
6 |
7 | import org.springframework.beans.BeansException;
8 | import org.springframework.context.ApplicationContext;
9 | import org.springframework.context.ApplicationContextAware;
10 |
11 | import io.github.tomdw.java.modules.context.boot.api.ModuleServiceReference;
12 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService;
13 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerWithGenericsService;
14 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NamedSpeakerService;
15 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService;
16 |
17 | @Named
18 | public class IntegrationTestUsingConstructorInjectionService implements ApplicationContextAware {
19 |
20 | private final SpeakerService speakerService;
21 |
22 | private final List multipleSpeakerServices;
23 |
24 | private final NamedSpeakerService namedSpeakerService;
25 |
26 | private final List> multipleSpeakerWithGenericsServices;
27 |
28 | private static ApplicationContext applicationContext;
29 |
30 | public IntegrationTestUsingConstructorInjectionService(
31 | @ModuleServiceReference SpeakerService speakerService,
32 | @ModuleServiceReference @Named("multipleSpeakerServiceList") List multipleSpeakerServices,
33 | @ModuleServiceReference NamedSpeakerService namedSpeakerService,
34 | @ModuleServiceReference @Named("multipleSpeakerWithGenericsServiceList") List> multipleSpeakerWithGenericsServices) {
35 | this.speakerService = speakerService;
36 | this.multipleSpeakerServices = multipleSpeakerServices;
37 | this.namedSpeakerService = namedSpeakerService;
38 | this.multipleSpeakerWithGenericsServices = multipleSpeakerWithGenericsServices;
39 | }
40 |
41 | public List getMultipleSpeakerServices() {
42 | return multipleSpeakerServices;
43 | }
44 |
45 | public NamedSpeakerService getNamedSpeakerService() {
46 | return namedSpeakerService;
47 | }
48 |
49 | public List> getMultipleSpeakerWithGenericsServices() { return multipleSpeakerWithGenericsServices; }
50 |
51 | public SpeakerService getSpeakerService() {
52 | return speakerService;
53 | }
54 |
55 | public static ApplicationContext getApplicationContext() {
56 | return applicationContext;
57 | }
58 |
59 | @Override
60 | public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
61 | this.applicationContext = applicationContext;
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/integration-tests/src/main/java/module-info.java:
--------------------------------------------------------------------------------
1 | import io.github.tomdw.java.modules.context.boot.api.ModuleContext;
2 | import io.github.tomdw.java.modules.spring.integration.tests.IntegrationTestConfiguration;
3 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.FailingSpeakerService;
4 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService;
5 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerWithGenericsService;
6 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NamedSpeakerService;
7 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService;
8 |
9 | @ModuleContext(mainConfigurationClass = IntegrationTestConfiguration.class)
10 | module io.github.tomdw.java.modules.spring.integration.tests {
11 | requires io.github.tomdw.java.modules.context.boot;
12 | requires io.github.tomdw.java.modules.spring.samples.basicapplication.application;
13 | requires io.github.tomdw.java.modules.spring.samples.basicapplication.speaker;
14 |
15 | uses SpeakerService;
16 | uses MultipleSpeakerService;
17 | uses NamedSpeakerService;
18 | uses MultipleSpeakerWithGenericsService;
19 | uses FailingSpeakerService;
20 |
21 | opens io.github.tomdw.java.modules.spring.integration.tests to spring.beans, spring.core, spring.context;
22 | }
--------------------------------------------------------------------------------
/integration-tests/src/test/java/io/github/tomdw/java/modules/spring/integration/tests/JavaModulesSpringContextBootIntegrationTest.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.spring.integration.tests;
2 |
3 | import static org.assertj.core.api.Assertions.assertThat;
4 | import static org.assertj.core.api.Assertions.assertThatThrownBy;
5 |
6 | import java.util.List;
7 | import java.util.ServiceLoader;
8 | import java.util.stream.Collectors;
9 |
10 | import org.junit.jupiter.api.AfterEach;
11 | import org.junit.jupiter.api.Test;
12 | import org.springframework.context.support.GenericApplicationContext;
13 |
14 | import io.github.tomdw.java.modules.context.boot.api.ModuleContextBooter;
15 | import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider;
16 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.FailingSpeakerService;
17 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService;
18 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerCheckedException;
19 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerRuntimeException;
20 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService;
21 |
22 | public class JavaModulesSpringContextBootIntegrationTest {
23 |
24 | @AfterEach
25 | public void reset() {
26 | ModuleContextBooter.reset();
27 | }
28 |
29 | @Test
30 | public void createsSpringApplicationContextForEveryModuleWithModuleContextAnnotation() {
31 | ModuleContextBooter.main();
32 |
33 | String[] expectedModuleNames = {"io.github.tomdw.java.modules.spring.samples.basicapplication.application",
34 | "io.github.tomdw.java.modules.spring.samples.basicapplication.speaker",
35 | "io.github.tomdw.java.modules.spring.integration.tests"};
36 | List modulesWithModuleContextAnnotation = ModuleLayer.boot().modules().stream().filter(module -> List.of(expectedModuleNames).contains(module.getName())).collect(Collectors.toList());
37 |
38 | assertThat(modulesWithModuleContextAnnotation.stream().map(Module::getName)).containsExactlyInAnyOrder(expectedModuleNames);
39 |
40 | modulesWithModuleContextAnnotation.forEach(
41 | module -> {
42 | GenericApplicationContext context = ModuleContextBooter.getContextFor(module);
43 | assertThat(context).withFailMessage("A context should have been created for module " + module.getName()).isNotNull();
44 | assertThat(context.isActive()).withFailMessage("The context should be active for module " + module.getName()).isTrue();
45 | }
46 | );
47 | }
48 |
49 | @Test
50 | public void singleServiceFromOtherModuleCanBeInjectedUsingModuleServiceReferenceOnField() {
51 | ModuleContextBooter.main();
52 |
53 | IntegrationTestService testConfig = IntegrationTestService.getApplicationContext().getBean(IntegrationTestService.class);
54 | assertThat(testConfig).isNotNull();
55 |
56 | assertThat(testConfig.getSpeakerService()).withFailMessage("No SpeakerService injected").isNotNull();
57 | assertThat(testConfig.getSpeakerService().getName()).withFailMessage("Wrong SpeakerService injected").isEqualTo("Default");
58 | }
59 |
60 | @Test
61 | public void serviceListFromOtherModuleCanBeInjectedUsingModuleServiceReferenceOnField() {
62 | ModuleContextBooter.main();
63 |
64 | IntegrationTestService testConfig = IntegrationTestService.getApplicationContext().getBean(IntegrationTestService.class);
65 | assertThat(testConfig).isNotNull();
66 |
67 | assertThat(testConfig.getMultipleSpeakerServices()).withFailMessage("No MultipleSpeakerService(s) injected").isNotNull();
68 | assertThat(testConfig.getMultipleSpeakerServices().stream().map(MultipleSpeakerService::getName)).containsExactlyInAnyOrder("Default", "Other");
69 | }
70 |
71 | @Test
72 | public void singleServiceFromOtherModuleCanBeRetrievedSpecificallyOnBeanNameOnField() {
73 | ModuleContextBooter.main();
74 |
75 | IntegrationTestService testConfig = IntegrationTestService.getApplicationContext().getBean(IntegrationTestService.class);
76 | assertThat(testConfig).isNotNull();
77 |
78 | assertThat(testConfig.getNamedSpeakerService().getSpeakerName()).isEqualTo("otherNamedSpeakerServiceName");
79 | }
80 |
81 | @Test
82 | public void serviceListFromOtherModuleWithGenericsCanBeInjectedUsingModuleServiceReferenceOnField() {
83 | ModuleContextBooter.main();
84 |
85 | IntegrationTestService testConfig = IntegrationTestService.getApplicationContext().getBean(IntegrationTestService.class);
86 | assertThat(testConfig).isNotNull();
87 |
88 | assertThat(testConfig.getMultipleSpeakerWithGenericsServices()).withFailMessage("No MultipleSpeakerWithGenericsService(s) injected").isNotNull();
89 | assertThat(testConfig.getMultipleSpeakerWithGenericsServices().get(0).getMultipleSpeakerName()).asString().isEqualTo("myMultipleGenericSpeakerName");
90 | }
91 |
92 | @Test
93 | public void singleServiceFromOtherModuleCanBeInjectedUsingModuleServiceReferenceOnConstructorParameter() {
94 | ModuleContextBooter.main();
95 |
96 | IntegrationTestUsingConstructorInjectionService testConfig = IntegrationTestUsingConstructorInjectionService.getApplicationContext().getBean(IntegrationTestUsingConstructorInjectionService.class);
97 | assertThat(testConfig).isNotNull();
98 |
99 | assertThat(testConfig.getSpeakerService()).withFailMessage("No SpeakerService injected").isNotNull();
100 | assertThat(testConfig.getSpeakerService().getName()).withFailMessage("Wrong SpeakerService injected").isEqualTo("Default");
101 | }
102 |
103 | @Test
104 | public void serviceListFromOtherModuleCanBeInjectedUsingModuleServiceReferenceOnConstructorParameter() {
105 | ModuleContextBooter.main();
106 |
107 | IntegrationTestUsingConstructorInjectionService testConfig = IntegrationTestService.getApplicationContext().getBean(IntegrationTestUsingConstructorInjectionService.class);
108 | assertThat(testConfig).isNotNull();
109 |
110 | assertThat(testConfig.getMultipleSpeakerServices()).withFailMessage("No MultipleSpeakerService(s) injected").isNotNull();
111 | assertThat(testConfig.getMultipleSpeakerServices().stream().map(MultipleSpeakerService::getName)).containsExactlyInAnyOrder("Default", "Other");
112 | }
113 |
114 | @Test
115 | public void singleServiceFromOtherModuleCanBeRetrievedSpecificallyOnBeanNameOnConstructorParameter() {
116 | ModuleContextBooter.main();
117 |
118 | IntegrationTestUsingConstructorInjectionService testConfig = IntegrationTestUsingConstructorInjectionService.getApplicationContext().getBean(IntegrationTestUsingConstructorInjectionService.class);
119 | assertThat(testConfig).isNotNull();
120 |
121 | assertThat(testConfig.getNamedSpeakerService().getSpeakerName()).isEqualTo("otherNamedSpeakerServiceName");
122 | }
123 |
124 | @Test
125 | public void serviceListFromOtherModuleWithGenericsCanBeInjectedUsingModuleServiceReferenceOnConstructorParameter() {
126 | ModuleContextBooter.main();
127 |
128 | IntegrationTestUsingConstructorInjectionService testConfig = IntegrationTestUsingConstructorInjectionService.getApplicationContext().getBean(IntegrationTestUsingConstructorInjectionService.class);
129 | assertThat(testConfig).isNotNull();
130 |
131 | assertThat(testConfig.getMultipleSpeakerWithGenericsServices()).withFailMessage("No MultipleSpeakerWithGenericsService(s) injected").isNotNull();
132 | assertThat(testConfig.getMultipleSpeakerWithGenericsServices().get(0).getMultipleSpeakerName()).asString().isEqualTo("myMultipleGenericSpeakerName");
133 | }
134 |
135 |
136 | @Test
137 | public void usingModuleServiceProviderBeforeExplicitBootIsSupported() {
138 | SpeakerService singleSpeakerService = ModuleServiceProvider.provide(SpeakerService.class);
139 | assertThat(singleSpeakerService).isNotNull();
140 |
141 | ModuleContextBooter.boot();
142 |
143 | GenericApplicationContext contextForModule = ModuleContextBooter.getContextFor(SpeakerService.class.getModule());
144 | assertThat(contextForModule).isNotNull();
145 | }
146 |
147 | @Test
148 | public void bootingModuleContextBooterMultipleTimesIsNotAProblem() {
149 | ModuleContextBooter.boot();
150 | ModuleContextBooter.boot();
151 |
152 | GenericApplicationContext contextForModule = ModuleContextBooter.getContextFor(SpeakerService.class.getModule());
153 | assertThat(contextForModule).isNotNull();
154 | }
155 |
156 | @Test
157 | public void aDynamicProxiedServiceShouldStillThrowExceptionsAsIfTheServiceIsNotProxiedMeaningExceptionsShouldNotBeWrappedInOtherExceptions() {
158 | ModuleContextBooter.main();
159 |
160 | ServiceLoader failingSpeakerServiceServiceLoader = ServiceLoader.load(FailingSpeakerService.class);
161 | FailingSpeakerService failingSpeakerService = failingSpeakerServiceServiceLoader.findFirst().orElseThrow();
162 |
163 | assertThatThrownBy(failingSpeakerService::getSpeakerNameButThrowsCheckedException).isInstanceOf(NoSpeakerCheckedException.class);
164 | assertThatThrownBy(failingSpeakerService::getSpeakerNameButThrowsRuntimeException).isInstanceOf(NoSpeakerRuntimeException.class);
165 | }
166 |
167 | }
168 |
--------------------------------------------------------------------------------
/java-modules-context-boot-starter/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | io.github.tomdw.java.modules.spring
5 | java-modules-context-boot-build
6 | 0.0.7-SNAPSHOT
7 |
8 | 4.0.0
9 |
10 | java-modules-context-boot-starter
11 |
12 |
13 |
14 | io.github.tomdw.java.modules.spring
15 | java-modules-context-boot
16 |
17 |
18 | org.springframework.boot
19 | spring-boot-starter
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/java-modules-context-boot-starter/src/main/java/io/github/tomdw/java/modules/context/boot/starter/JavaModulesContextBootApplicationContextInitializer.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.context.boot.starter;
2 |
3 | import org.springframework.context.ApplicationContextInitializer;
4 | import org.springframework.context.support.GenericApplicationContext;
5 | import org.springframework.core.Ordered;
6 | import org.springframework.core.annotation.Order;
7 | import org.springframework.stereotype.Component;
8 |
9 | import io.github.tomdw.java.modules.context.boot.api.ModuleContextBooter;
10 |
11 | @Component
12 | @Order(Ordered.HIGHEST_PRECEDENCE)
13 | public class JavaModulesContextBootApplicationContextInitializer implements ApplicationContextInitializer {
14 |
15 | private static final System.Logger LOGGER = System.getLogger(JavaModulesContextBootApplicationContextInitializer.class.getName());
16 |
17 | @Override
18 | public void initialize(GenericApplicationContext applicationContext) {
19 | LOGGER.log(System.Logger.Level.INFO, "Spring Boot Starter for Java Module Context activated ...");
20 | ModuleContextBooter.boot(applicationContext);
21 | LOGGER.log(System.Logger.Level.INFO, "Spring Boot Starter for Java Module Context finished.");
22 | }
23 | }
24 |
25 |
--------------------------------------------------------------------------------
/java-modules-context-boot-starter/src/main/java/module-info.java:
--------------------------------------------------------------------------------
1 | open module io.github.tomdw.java.modules.context.boot.starter {
2 | requires spring.beans;
3 | requires spring.context;
4 | requires io.github.tomdw.java.modules.context.boot;
5 | }
--------------------------------------------------------------------------------
/java-modules-context-boot-starter/src/main/resources/META-INF/spring.factories:
--------------------------------------------------------------------------------
1 | org.springframework.context.ApplicationContextInitializer=io.github.tomdw.java.modules.context.boot.starter.JavaModulesContextBootApplicationContextInitializer
--------------------------------------------------------------------------------
/java-modules-context-boot/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | io.github.tomdw.java.modules.spring
5 | java-modules-context-boot-build
6 | 0.0.7-SNAPSHOT
7 |
8 | 4.0.0
9 |
10 | java-modules-context-boot
11 |
12 |
13 |
14 |
15 | org.codehaus.mojo
16 | exec-maven-plugin
17 |
18 |
19 |
20 |
21 |
22 |
23 | org.springframework
24 | spring-beans
25 |
26 |
27 | org.springframework
28 | spring-core
29 |
30 |
31 | org.springframework
32 | spring-context
33 |
34 |
35 | jakarta.inject
36 | jakarta.inject-api
37 |
38 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleContext.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.context.boot.api;
2 |
3 | import java.lang.annotation.Documented;
4 | import java.lang.annotation.ElementType;
5 | import java.lang.annotation.Retention;
6 | import java.lang.annotation.RetentionPolicy;
7 | import java.lang.annotation.Target;
8 |
9 | import org.springframework.context.annotation.AnnotationConfigApplicationContext;
10 | import org.springframework.context.annotation.Configuration;
11 | import org.springframework.context.support.GenericApplicationContext;
12 |
13 | @Retention(RetentionPolicy.RUNTIME)
14 | @Target(ElementType.MODULE)
15 | @Documented
16 | public @interface ModuleContext {
17 |
18 | Class> mainConfigurationClass() default NoConfiguration.class;
19 |
20 | Class extends GenericApplicationContext> applicationContextClass() default AnnotationConfigApplicationContext.class;
21 |
22 | @Configuration
23 | class NoConfiguration {
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleContextBooter.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.context.boot.api;
2 |
3 | import org.springframework.context.support.GenericApplicationContext;
4 |
5 | import io.github.tomdw.java.modules.context.boot.internal.ModuleContextRegistry;
6 |
7 | public class ModuleContextBooter {
8 |
9 | public static void boot() {
10 | ModuleContextRegistry.boot();
11 | }
12 |
13 | public static void boot(GenericApplicationContext defaultApplicationContext) {
14 | ModuleContextRegistry.boot(defaultApplicationContext);
15 | }
16 |
17 | public static void reset() {
18 | ModuleContextRegistry.reset();
19 | }
20 |
21 | public static GenericApplicationContext getContextFor(Module module) {
22 | return ModuleContextRegistry.getContextFor(module);
23 | }
24 |
25 | public static void main(String... commandLineArguments) {
26 | ModuleContextBooter.boot();
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleServiceProvider.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.context.boot.api;
2 |
3 | import io.github.tomdw.java.modules.context.boot.internal.ModuleContextRegistry;
4 |
5 | public class ModuleServiceProvider {
6 |
7 | public static SERVICETYPE provide(Class servicetypeClass) {
8 | return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass);
9 | }
10 |
11 | public static SERVICETYPE provide(Class servicetypeClass, String serviceName) {
12 | return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass, serviceName);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleServiceReference.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.context.boot.api;
2 |
3 | import java.lang.annotation.ElementType;
4 | import java.lang.annotation.Retention;
5 | import java.lang.annotation.RetentionPolicy;
6 | import java.lang.annotation.Target;
7 |
8 | import org.springframework.beans.factory.annotation.Autowired;
9 |
10 | @Retention(RetentionPolicy.RUNTIME)
11 | @Target({ElementType.FIELD,ElementType.PARAMETER})
12 | @Autowired
13 | public @interface ModuleServiceReference {
14 | }
15 |
--------------------------------------------------------------------------------
/java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/internal/ApplicationContextInstantiationException.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.context.boot.internal;
2 |
3 | public class ApplicationContextInstantiationException extends RuntimeException {
4 |
5 | public ApplicationContextInstantiationException(Exception cause) {
6 | super(cause);
7 | }
8 |
9 | }
10 |
--------------------------------------------------------------------------------
/java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/internal/InactiveDefaultApplicationContextException.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.context.boot.internal;
2 |
3 | public class InactiveDefaultApplicationContextException extends IllegalStateException {
4 |
5 | public InactiveDefaultApplicationContextException(Module module, Class serviceClass) {
6 | super(String.format("Unable to provide instance of %s from module %s that is part of the default application context which is still inactive. Beans cannot be loaded from the default application context before it is active. Lazy load services or retry loading after startup.",
7 | serviceClass.getSimpleName(), module.getName()));
8 | }
9 | }
10 |
11 |
--------------------------------------------------------------------------------
/java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/internal/LazyRetrieveBeanFromContextStrategy.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.context.boot.internal;
2 |
3 | import static java.lang.System.Logger.Level.DEBUG;
4 | import static java.lang.System.Logger.Level.INFO;
5 | import static java.lang.System.Logger.Level.WARNING;
6 |
7 | import java.lang.reflect.InvocationHandler;
8 | import java.lang.reflect.InvocationTargetException;
9 | import java.lang.reflect.Method;
10 | import java.lang.reflect.Proxy;
11 |
12 | import org.springframework.context.support.GenericApplicationContext;
13 |
14 | abstract class LazyRetrieveBeanFromContextStrategy implements InvocationHandler {
15 | private static final System.Logger LOGGER = System.getLogger(LazyRetrieveBeanFromContextStrategy.class.getName());
16 |
17 | protected final Module moduleToRetrieveFrom;
18 | protected final GenericApplicationContext defaultApplicationContext;
19 | protected final GenericApplicationContext context;
20 | protected final Class serviceClass;
21 |
22 | protected LazyRetrieveBeanFromContextStrategy(Module moduleToRetrieveFrom, GenericApplicationContext defaultApplicationContext, GenericApplicationContext context, Class serviceClass) {
23 | this.moduleToRetrieveFrom = moduleToRetrieveFrom;
24 | this.defaultApplicationContext = defaultApplicationContext;
25 | this.context = context;
26 | this.serviceClass = serviceClass;
27 | }
28 |
29 | static LazyRetrieveBeanFromContextStrategy withoutServiceName(Module moduleToRetrieveFrom, GenericApplicationContext defaultApplicationContext, GenericApplicationContext context, Class serviceClass) {
30 | return new LazyRetrieveBeanFromContextWithoutServiceNameStrategy<>(moduleToRetrieveFrom, defaultApplicationContext, context, serviceClass);
31 | }
32 |
33 | static LazyRetrieveBeanFromContextStrategy withServiceName(Module moduleToRetrieveFrom, GenericApplicationContext defaultApplicationContext, GenericApplicationContext context, Class serviceClass, String serviceName) {
34 | return new LazyRetrieveBeanFromContextWithServiceNameStrategy<>(moduleToRetrieveFrom, defaultApplicationContext, context, serviceClass, serviceName);
35 | }
36 |
37 | SERVICETYPE retrieveInstanceFromContext() {
38 | if (serviceClass.isInterface()) {
39 | LOGGER.log(DEBUG, "Providing dynamic proxy for " + logMessageDescribingInstanceToProvide() + " from module " + moduleToRetrieveFrom.getName());
40 | return createDynamicProxyToPostponeContextLoadingUntilInvocationOfService();
41 | } else {
42 | LOGGER.log(WARNING, "Bean was provided as implementation, better to provide interfaces so dynamic proxies are created: " + serviceClass);
43 | lazyStartApplicationContextForModule();
44 | LOGGER.log(DEBUG, "Providing " + logMessageDescribingInstanceToProvide() + " from module " + moduleToRetrieveFrom.getName());
45 | return getBeanFromContext();
46 | }
47 | }
48 |
49 | @SuppressWarnings("unchecked")
50 | private SERVICETYPE createDynamicProxyToPostponeContextLoadingUntilInvocationOfService() {
51 | return (SERVICETYPE) Proxy.newProxyInstance(
52 | moduleToRetrieveFrom.getClassLoader(),
53 | new Class[] { serviceClass },
54 | this);
55 | }
56 |
57 | @Override
58 | public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
59 | lazyStartApplicationContextForModule();
60 | LOGGER.log(DEBUG, "Resolving dynamic proxy for " + logMessageDescribingInstanceToProvide() + " from ApplicationContext for module " + moduleToRetrieveFrom.getName());
61 | try {
62 | return method.invoke(getBeanFromContext(), args);
63 | } catch (InvocationTargetException ite) {
64 | throw ite.getTargetException();
65 | }
66 | }
67 |
68 | private void lazyStartApplicationContextForModule() {
69 | if (!context.isActive()) {
70 | if (context.equals(defaultApplicationContext)) {
71 | throw new InactiveDefaultApplicationContextException(moduleToRetrieveFrom, serviceClass);
72 | }
73 | LOGGER.log(INFO, "Lazy starting ApplicationContext for module " + moduleToRetrieveFrom.getName());
74 | context.refresh();
75 | }
76 | }
77 |
78 | protected abstract SERVICETYPE getBeanFromContext();
79 |
80 | protected abstract String logMessageDescribingInstanceToProvide();
81 |
82 | }
--------------------------------------------------------------------------------
/java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/internal/LazyRetrieveBeanFromContextWithServiceNameStrategy.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.context.boot.internal;
2 |
3 | import org.springframework.context.support.GenericApplicationContext;
4 |
5 | class LazyRetrieveBeanFromContextWithServiceNameStrategy extends LazyRetrieveBeanFromContextStrategy {
6 |
7 | private final String serviceName;
8 |
9 | LazyRetrieveBeanFromContextWithServiceNameStrategy(Module moduleToRetrieveFrom, GenericApplicationContext defaultApplicationContext, GenericApplicationContext context, Class serviceClass, String serviceName) {
10 | super(moduleToRetrieveFrom, defaultApplicationContext, context, serviceClass);
11 | this.serviceName = serviceName;
12 | }
13 |
14 | @Override
15 | protected SERVICETYPE getBeanFromContext() {
16 | return context.getBean(serviceName, serviceClass);
17 | }
18 |
19 | @Override
20 | protected String logMessageDescribingInstanceToProvide() {
21 | return "instance of " + serviceClass.getSimpleName() + " with name '" + serviceName + "'";
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/internal/LazyRetrieveBeanFromContextWithoutServiceNameStrategy.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.context.boot.internal;
2 |
3 | import org.springframework.context.support.GenericApplicationContext;
4 |
5 | class LazyRetrieveBeanFromContextWithoutServiceNameStrategy extends LazyRetrieveBeanFromContextStrategy {
6 | LazyRetrieveBeanFromContextWithoutServiceNameStrategy(Module moduleToRetrieveFrom, GenericApplicationContext defaultApplicationContext, GenericApplicationContext context, Class serviceClass) {
7 | super(moduleToRetrieveFrom, defaultApplicationContext, context, serviceClass);
8 | }
9 |
10 | @Override
11 | protected SERVICETYPE getBeanFromContext() {
12 | return context.getBean(serviceClass);
13 | }
14 |
15 | @Override
16 | protected String logMessageDescribingInstanceToProvide() {
17 | return "instance of " + serviceClass.getSimpleName();
18 | }
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/internal/ModuleContextRegistry.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.context.boot.internal;
2 |
3 | import static java.lang.System.Logger.Level.DEBUG;
4 | import static java.lang.System.Logger.Level.INFO;
5 |
6 | import java.lang.reflect.InvocationTargetException;
7 | import java.util.HashMap;
8 | import java.util.Map;
9 |
10 | import org.springframework.context.annotation.AnnotationConfigRegistry;
11 | import org.springframework.context.support.GenericApplicationContext;
12 |
13 | import io.github.tomdw.java.modules.context.boot.api.ModuleContext;
14 |
15 | public class ModuleContextRegistry {
16 | private static final System.Logger LOGGER = System.getLogger(ModuleContextRegistry.class.getName());
17 |
18 | private static final Map moduleContexts = new HashMap<>();
19 | private static GenericApplicationContext defaultApplicationContext;
20 |
21 | private ModuleContextRegistry() {}
22 |
23 | public static void reset() {
24 | defaultApplicationContext = null;
25 | moduleContexts.clear();
26 | }
27 |
28 | private static void register(Module module, GenericApplicationContext applicationContext) {
29 | synchronized (moduleContexts) {
30 | LOGGER.log(DEBUG, "Registering spring application context for module " + module.getName());
31 | if (moduleContexts.containsKey(module)) {
32 | throw new IllegalStateException("An application context for module " + module.getName() + " was already registered");
33 | }
34 | moduleContexts.put(module, applicationContext);
35 | }
36 | }
37 |
38 | private static GenericApplicationContext getOrPrepareContextFor(Module module) {
39 | prepareApplicationContextForModuleIfNeeded(module);
40 | synchronized (moduleContexts) {
41 | if (moduleContexts.containsKey(module)) {
42 | return moduleContexts.get(module);
43 | } else if (defaultApplicationContext != null) {
44 | return defaultApplicationContext;
45 | } else {
46 | throw new IllegalStateException("No Application context found for module " + module.getName());
47 | }
48 |
49 | }
50 | }
51 |
52 | private static void prepareApplicationContextForModuleIfNeeded(Module module) {
53 | if (module.isAnnotationPresent(ModuleContext.class)) {
54 | synchronized (moduleContexts) {
55 | if (!moduleContexts.containsKey(module)) {
56 | prepareApplicationContextFor(module);
57 | }
58 | }
59 | }
60 | }
61 |
62 | public static SERVICETYPE retrieveInstanceFromContext(Class serviceClass) {
63 | Module moduleToRetrieveFrom = getCallerModule();
64 | GenericApplicationContext context = getOrPrepareContextFor(moduleToRetrieveFrom);
65 | return LazyRetrieveBeanFromContextStrategy
66 | .withoutServiceName(moduleToRetrieveFrom, defaultApplicationContext, context, serviceClass)
67 | .retrieveInstanceFromContext();
68 | }
69 |
70 | public static SERVICETYPE retrieveInstanceFromContext(Class serviceClass, String serviceName) {
71 | Module moduleToRetrieveFrom = getCallerModule();
72 | GenericApplicationContext context = getOrPrepareContextFor(moduleToRetrieveFrom);
73 | return LazyRetrieveBeanFromContextStrategy
74 | .withServiceName(moduleToRetrieveFrom, defaultApplicationContext, context, serviceClass, serviceName)
75 | .retrieveInstanceFromContext();
76 | }
77 |
78 | private static void provisionForLayer(ModuleLayer layer) {
79 | LOGGER.log(INFO, "Preparing modular spring application");
80 | for (Module module : layer.modules()) {
81 | if (module.isAnnotationPresent(ModuleContext.class)) {
82 | prepareApplicationContextForModuleIfNeeded(module);
83 | }
84 | }
85 | }
86 |
87 | public static void boot(ModuleLayer layer) {
88 | provisionForLayer(layer);
89 | LOGGER.log(INFO, "Booting modular spring application");
90 | synchronized (moduleContexts) {
91 | for (Map.Entry contextEntry : moduleContexts.entrySet()) {
92 | Module module = contextEntry.getKey();
93 | GenericApplicationContext context = contextEntry.getValue();
94 | if (!context.isActive()) {
95 | LOGGER.log(INFO, "Starting ApplicationContext for Module " + module.getName());
96 | context.refresh();
97 | } else {
98 | LOGGER.log(INFO, "ApplicationContext for Module " + module.getName() + " is already active");
99 | }
100 | }
101 | }
102 | }
103 |
104 | public static void boot() {
105 | boot(ModuleLayer.boot());
106 | }
107 |
108 | public static void boot(GenericApplicationContext defaultApplicationContext) {
109 | ModuleContextRegistry.defaultApplicationContext = defaultApplicationContext;
110 | enhanceApplicationContext(defaultApplicationContext);
111 | boot();
112 | }
113 |
114 | private static void prepareApplicationContextFor(Module module) {
115 | ModuleContext moduleContext = module.getAnnotation(ModuleContext.class);
116 | Class> mainConfigurationClass = moduleContext.mainConfigurationClass();
117 | LOGGER.log(INFO, "Preparing ApplicationContext for Module " + module.getName() + " using config class " + mainConfigurationClass.getSimpleName());
118 | GenericApplicationContext context = instantiateApplicationContext(moduleContext);
119 | context.setId("module-context-" + module.getName());
120 | AnnotationConfigRegistry annotationConfigRegistry = asAnnotationConfigRegistry(context);
121 | annotationConfigRegistry.register(mainConfigurationClass);
122 | enhanceApplicationContext(context);
123 | register(module, context);
124 | }
125 |
126 | private static void enhanceApplicationContext(GenericApplicationContext context) {
127 | AnnotationConfigRegistry annotationConfigRegistry = asAnnotationConfigRegistry(context);
128 | annotationConfigRegistry.register(ModuleServiceReferenceAnnotationPostProcessor.class);
129 | if (defaultApplicationContext != null && context != defaultApplicationContext) {
130 | context.setEnvironment(defaultApplicationContext.getEnvironment());
131 | }
132 | }
133 |
134 | private static GenericApplicationContext instantiateApplicationContext(ModuleContext moduleContext) {
135 | try {
136 | return moduleContext.applicationContextClass().getDeclaredConstructor().newInstance();
137 | } catch (InstantiationException e) {
138 | LOGGER.log(System.Logger.Level.ERROR, "Cannot instantiate " + moduleContext.applicationContextClass());
139 | throw new ApplicationContextInstantiationException(e);
140 | } catch (IllegalAccessException e) {
141 | LOGGER.log(System.Logger.Level.ERROR, "No access to default constructor of " + moduleContext.applicationContextClass());
142 | throw new ApplicationContextInstantiationException(e);
143 | } catch (InvocationTargetException e) {
144 | LOGGER.log(System.Logger.Level.ERROR, "Cannot invoke default constructor of " + moduleContext.applicationContextClass());
145 | throw new ApplicationContextInstantiationException(e);
146 | } catch (NoSuchMethodException e) {
147 | LOGGER.log(System.Logger.Level.ERROR, "No Default constructor for " + moduleContext.applicationContextClass());
148 | throw new ApplicationContextInstantiationException(e);
149 | }
150 | }
151 |
152 | private static AnnotationConfigRegistry asAnnotationConfigRegistry(GenericApplicationContext context) {
153 | try {
154 | return (AnnotationConfigRegistry) context;
155 | } catch (ClassCastException e) {
156 | LOGGER.log(System.Logger.Level.ERROR, "The provided Application Context type " + context.getClass() + " should implement org.springframework.context.annotation.AnnotationConfigRegistry");
157 | throw new ApplicationContextInstantiationException(e);
158 | }
159 | }
160 |
161 | private static Module getCallerModule() {
162 | return StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE)
163 | .walk(stackFrameStream -> stackFrameStream
164 | .map(StackWalker.StackFrame::getDeclaringClass)
165 | .map(Class::getModule)
166 | .filter(module -> module != ModuleContextRegistry.class.getModule())
167 | .findFirst()
168 | .orElseThrow(() -> new UnsupportedOperationException("Can only get an application context for a Module annotated with @ModuleContext")));
169 | }
170 |
171 | public static GenericApplicationContext getContextFor(Module module) {
172 | return getOrPrepareContextFor(module);
173 | }
174 | }
--------------------------------------------------------------------------------
/java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/internal/ModuleServiceReferenceAnnotationPostProcessor.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.context.boot.internal;
2 |
3 | import static java.lang.System.Logger.Level.ERROR;
4 | import static java.lang.System.Logger.Level.INFO;
5 |
6 | import java.lang.reflect.Constructor;
7 | import java.lang.reflect.Field;
8 | import java.lang.reflect.Parameter;
9 |
10 | import javax.inject.Named;
11 |
12 | import org.springframework.beans.BeansException;
13 | import org.springframework.beans.factory.BeanCreationException;
14 | import org.springframework.beans.factory.BeanFactory;
15 | import org.springframework.beans.factory.BeanFactoryAware;
16 | import org.springframework.beans.factory.config.ConfigurableBeanFactory;
17 | import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
18 | import org.springframework.beans.factory.serviceloader.AbstractServiceLoaderBasedFactoryBean;
19 | import org.springframework.beans.factory.serviceloader.ServiceFactoryBean;
20 | import org.springframework.beans.factory.serviceloader.ServiceListFactoryBean;
21 |
22 | import io.github.tomdw.java.modules.context.boot.api.ModuleServiceReference;
23 |
24 | @Named
25 | public class ModuleServiceReferenceAnnotationPostProcessor implements InstantiationAwareBeanPostProcessor, BeanFactoryAware {
26 | private static final System.Logger LOGGER = System.getLogger(ModuleServiceReferenceAnnotationPostProcessor.class.getName());
27 |
28 | private ConfigurableBeanFactory beanFactory;
29 |
30 | @Override
31 | public Object postProcessBeforeInstantiation(Class> beanClass, String beanName) throws BeansException {
32 | Module usingModule = beanClass.getModule();
33 | for (Field field : beanClass.getDeclaredFields()) {
34 | if (field.isAnnotationPresent(ModuleServiceReference.class)) {
35 | postProcessModuleServiceReference(usingModule, ModuleServiceReferenceElement.of(field));
36 | }
37 | }
38 | for (Constructor> constructor: beanClass.getDeclaredConstructors()) {
39 | for(Parameter constructorParameter: constructor.getParameters()) {
40 | if (constructorParameter.isAnnotationPresent(ModuleServiceReference.class)) {
41 | postProcessModuleServiceReference(usingModule, ModuleServiceReferenceElement.of(constructorParameter));
42 | }
43 | }
44 | }
45 | return null;
46 | }
47 |
48 | private void postProcessModuleServiceReference(Module usingModule, ModuleServiceReferenceElement serviceReferenceElement) {
49 | if(serviceReferenceElement.isServicesList()) {
50 | registerServiceListFactoryBean(usingModule, serviceReferenceElement);
51 | } else {
52 | registerServiceFactoryBean(usingModule, serviceReferenceElement);
53 | }
54 | }
55 |
56 | private void registerServiceFactoryBean(Module usingModule, ModuleServiceReferenceElement serviceReferenceElement) {
57 | Class> serviceType = serviceReferenceElement.getModuleServiceType();
58 | LOGGER.log(INFO, "ModuleServiceReference from module " + usingModule.getName() + " found for service of type " + serviceType);
59 | validateModuleUsesServiceType(usingModule, serviceType);
60 | String newBeanName = serviceReferenceElement.getBeanNameToUseForServiceFactory();
61 | if(!this.beanFactory.containsBean(newBeanName)) {
62 | registerAbstractServiceFactoryBean(serviceType, newBeanName, new ServiceFactoryBean());
63 | }
64 | }
65 |
66 | private void registerServiceListFactoryBean(Module usingModule, ModuleServiceReferenceElement serviceReferenceElement) {
67 | Class> serviceType = serviceReferenceElement.getModuleServiceType();
68 | LOGGER.log(INFO, "ModuleServiceReference from module " + usingModule.getName() + " found for service of type List of " + serviceType);
69 | validateModuleUsesServiceType(usingModule, serviceType);
70 | String newBeanName = serviceReferenceElement.getBeanNameToUseForServiceFactory();
71 | if (!this.beanFactory.containsBean(newBeanName)) {
72 | registerAbstractServiceFactoryBean(serviceType, newBeanName, new ServiceListFactoryBean());
73 | }
74 | }
75 |
76 | private void registerAbstractServiceFactoryBean(Class> serviceType, String newBeanName, AbstractServiceLoaderBasedFactoryBean serviceFactoryBean) {
77 | serviceFactoryBean.setServiceType(serviceType);
78 | try {
79 | serviceFactoryBean.afterPropertiesSet();
80 | } catch (Exception e) {
81 | throw new BeanCreationException(newBeanName, e.getMessage(), e);
82 | }
83 | this.beanFactory.registerSingleton(newBeanName, serviceFactoryBean);
84 | }
85 |
86 | private void validateModuleUsesServiceType(Module usingModule, Class> serviceType) {
87 | if (!usingModule.canUse(serviceType)) {
88 | LOGGER.log(ERROR, "Module with name " + usingModule.getName() + " does not define a 'use' dependency on service of type: use " + serviceType.getName());
89 | throw new IllegalStateException("Module with name " + usingModule.getName() + " does not define a 'use' dependency on service of type: use " + serviceType.getName());
90 | }
91 | }
92 |
93 | @Override
94 | public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
95 | this.beanFactory = (ConfigurableBeanFactory) beanFactory;
96 | }
97 | }
--------------------------------------------------------------------------------
/java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/internal/ModuleServiceReferenceElement.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.context.boot.internal;
2 |
3 | import static java.lang.System.Logger.Level.ERROR;
4 |
5 | import java.lang.reflect.AnnotatedElement;
6 | import java.lang.reflect.Field;
7 | import java.lang.reflect.Parameter;
8 | import java.lang.reflect.ParameterizedType;
9 | import java.lang.reflect.Type;
10 | import java.util.List;
11 |
12 | import javax.inject.Named;
13 |
14 | import org.springframework.beans.factory.annotation.Qualifier;
15 |
16 | import io.github.tomdw.java.modules.context.boot.api.ModuleServiceReference;
17 |
18 | public class ModuleServiceReferenceElement {
19 |
20 | private static final System.Logger LOGGER = System.getLogger(ModuleServiceReferenceElement.class.getName());
21 |
22 | private final Class> declaredType;
23 | private final Class> moduleServiceType;
24 |
25 | public static ModuleServiceReferenceElement of(Field field) {
26 | return new ModuleServiceReferenceElement(field, field.getType(), field.getGenericType());
27 | }
28 |
29 | public static ModuleServiceReferenceElement of(Parameter parameter) {
30 | return new ModuleServiceReferenceElement(parameter, parameter.getType(), parameter.getParameterizedType());
31 | }
32 |
33 | private ModuleServiceReferenceElement(AnnotatedElement annotatedElement, Class> declaredType, Type genericTypeForServicesList) {
34 | validateModuleServiceReferenceAnnotationIsPresent(annotatedElement);
35 | this.declaredType = declaredType;
36 | this.moduleServiceType = determineModuleServiceType(declaredType, genericTypeForServicesList);
37 | if (isServicesList()) {
38 | validateListIsReferencedUsingAName(annotatedElement);
39 | }
40 | }
41 |
42 | private void validateModuleServiceReferenceAnnotationIsPresent(AnnotatedElement annotatedElement) {
43 | if (!annotatedElement.isAnnotationPresent(ModuleServiceReference.class)) {
44 | throw new IllegalArgumentException(ModuleServiceReferenceElement.class.getSimpleName() + " needs to be annotated with annotation " + ModuleServiceReference.class.getSimpleName());
45 | }
46 | }
47 |
48 | private void validateListIsReferencedUsingAName(AnnotatedElement annotatedElement) {
49 | if(!this.isReferencedUsingName(annotatedElement)) {
50 | LOGGER.log(ERROR, "Injecting a list of " + moduleServiceType.getName() + " requires a Qualifier or Named annotation with value " + getBeanNameToUseForServiceFactory());
51 | throw new IllegalStateException("Injecting a list of " + moduleServiceType.getName() + " requires a Qualifier or Named annotation with value " + getBeanNameToUseForServiceFactory());
52 | }
53 | }
54 |
55 | String getBeanNameToUseForServiceFactory() {
56 | String name = decapitalizeFirstLetter(moduleServiceType.getSimpleName());
57 | if (isServicesList()) {
58 | name += "List";
59 | }
60 | return name;
61 | }
62 |
63 | private String decapitalizeFirstLetter(String input) {
64 | return Character.toLowerCase(input.charAt(0)) + input.substring(1);
65 | }
66 |
67 | boolean isServicesList() {
68 | return declaredType.isAssignableFrom(List.class);
69 | }
70 |
71 | Class> getModuleServiceType() {
72 | return moduleServiceType;
73 | }
74 |
75 | private Class> determineModuleServiceType(Class> declaredType, Type genericTypeForServicesList) {
76 | if (isServicesList()) {
77 | ParameterizedType listGenericType = (ParameterizedType) genericTypeForServicesList;
78 | if (checkIfContentOfGenericListHasGenerics(listGenericType)) {
79 | return (Class>) ((ParameterizedType) listGenericType.getActualTypeArguments()[0]).getRawType();
80 | } else {
81 | return (Class>) listGenericType.getActualTypeArguments()[0];
82 | }
83 | } else {
84 | return declaredType;
85 | }
86 | }
87 |
88 | private boolean checkIfContentOfGenericListHasGenerics(ParameterizedType listGenericType) {
89 | return listGenericType.getActualTypeArguments()[0] instanceof ParameterizedType;
90 | }
91 |
92 | private boolean isReferencedUsingName(AnnotatedElement annotatedElement) {
93 | String referenceName = getBeanNameToUseForServiceFactory();
94 | if(annotatedElement.isAnnotationPresent(Named.class)) {
95 | return annotatedElement.getAnnotation(Named.class).value().equals(referenceName);
96 | }
97 | if(annotatedElement.isAnnotationPresent(Qualifier.class)) {
98 | return annotatedElement.getAnnotation(Qualifier.class).value().equals(referenceName);
99 | }
100 | return false;
101 | }
102 | }
103 |
--------------------------------------------------------------------------------
/java-modules-context-boot/src/main/java/module-info.java:
--------------------------------------------------------------------------------
1 | module io.github.tomdw.java.modules.context.boot {
2 | exports io.github.tomdw.java.modules.context.boot.api;
3 | requires transitive spring.context;
4 | requires transitive spring.beans;
5 | requires transitive spring.core;
6 | requires transitive java.inject;
7 |
8 | opens io.github.tomdw.java.modules.context.boot.internal to spring.beans, spring.core, spring.context;
9 | }
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 4.0.0
4 |
5 |
6 | io.github.tomdw.java.modules
7 | java-modules-parent
8 | 0.0.3
9 |
10 |
11 |
12 | io.github.tomdw.java.modules.spring
13 | java-modules-context-boot-build
14 | 0.0.7-SNAPSHOT
15 |
16 | java-modules-context-boot
17 | java-modules-context-boot-starter
18 | samples
19 | integration-tests
20 | integration-tests-spring-boot
21 |
22 | pom
23 |
24 |
25 | 5.3.23
26 | 2.7.3
27 | 1.0.5
28 | 3.23.1
29 | 5.9.0
30 |
31 |
32 |
33 |
34 | org.junit.jupiter
35 | junit-jupiter
36 |
37 |
38 | org.assertj
39 | assertj-core
40 |
41 |
42 |
43 |
44 |
45 |
46 | io.github.tomdw.java.modules.spring
47 | java-modules-context-boot
48 | ${project.version}
49 |
50 |
51 | io.github.tomdw.java.modules.spring
52 | java-modules-context-boot-starter
53 | ${project.version}
54 |
55 |
56 | org.springframework
57 | spring-core
58 | ${version.springframework}
59 | provided
60 |
61 |
62 | org.springframework
63 | spring-beans
64 | ${version.springframework}
65 | provided
66 |
67 |
68 | org.springframework
69 | spring-context
70 | ${version.springframework}
71 | provided
72 |
73 |
74 | org.springframework.boot
75 | spring-boot-starter
76 | ${spring-boot.version}
77 | provided
78 |
79 |
80 | jakarta.inject
81 | jakarta.inject-api
82 | ${version.jakarta.inject}
83 |
84 |
85 |
86 |
87 | org.junit
88 | junit-bom
89 | ${version.junit-jupiter}
90 | pom
91 | import
92 |
93 |
94 | org.assertj
95 | assertj-core
96 | ${version.assertj-core}
97 | test
98 |
99 |
100 | org.springframework.boot
101 | spring-boot-starter-test
102 | ${spring-boot.version}
103 | test
104 |
105 |
106 |
107 | io.github.tomdw.java.modules.spring.samples.basicapplication
108 | application
109 | ${project.version}
110 |
111 |
112 | io.github.tomdw.java.modules.spring.samples.basicapplication
113 | speaker
114 | ${project.version}
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 | org.apache.maven.plugins
123 | maven-enforcer-plugin
124 | 1.4.1
125 |
126 |
127 | enforce-maven
128 |
129 | enforce
130 |
131 |
132 |
133 |
134 | 3.6
135 |
136 |
137 |
138 |
139 |
140 |
141 |
142 |
143 |
144 |
145 | org.codehaus.mojo
146 | versions-maven-plugin
147 | 2.8.1
148 |
149 | file:///${project.basedir}/dependency-upgrade-rules.xml
150 | false
151 | false
152 | false
153 |
154 |
155 |
156 |
157 |
158 |
159 |
--------------------------------------------------------------------------------
/samples/basicapplication/application/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | io.github.tomdw.java.modules.spring.samples.basicapplication
5 | basic-application
6 | 0.0.7-SNAPSHOT
7 |
8 | 4.0.0
9 |
10 | application
11 |
12 |
13 |
14 | io.github.tomdw.java.modules.spring
15 | java-modules-context-boot
16 |
17 |
18 | io.github.tomdw.java.modules.spring.samples.basicapplication
19 | speaker
20 |
21 |
22 |
23 |
24 |
25 |
26 |
28 | org.codehaus.mojo
29 | exec-maven-plugin
30 | false
31 |
32 |
33 | default-cli
34 |
35 | java
36 |
37 | --show-module-resolution
38 | --add-modules
39 |
40 | java.sql,io.github.tomdw.java.modules.spring.samples.basicapplication.application
41 |
42 | --module-path
43 |
44 | --module
45 |
46 | io.github.tomdw.java.modules.context.boot/io.github.tomdw.java.modules.context.boot.api.ModuleContextBooter
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
--------------------------------------------------------------------------------
/samples/basicapplication/application/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/internal/MainApplicationConfiguration.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.spring.samples.basicapplication.internal;
2 |
3 | import org.springframework.context.annotation.ComponentScan;
4 | import org.springframework.context.annotation.Configuration;
5 |
6 | @Configuration
7 | @ComponentScan
8 | public class MainApplicationConfiguration {
9 |
10 | }
11 |
--------------------------------------------------------------------------------
/samples/basicapplication/application/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/internal/MessageGenerator.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.spring.samples.basicapplication.internal;
2 |
3 | import java.util.List;
4 |
5 | import javax.inject.Named;
6 |
7 | import org.springframework.beans.factory.InitializingBean;
8 |
9 | import io.github.tomdw.java.modules.context.boot.api.ModuleServiceReference;
10 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService;
11 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService;
12 |
13 | @Named
14 | public class MessageGenerator implements InitializingBean {
15 |
16 | @ModuleServiceReference
17 | private SpeakerService speakerService;
18 |
19 | @ModuleServiceReference
20 | @Named("multipleSpeakerServiceList")
21 | private List multipleSpeakerServices;
22 |
23 | @Override
24 | public void afterPropertiesSet() throws Exception {
25 | this.speakerService.speak("Hello World!");
26 | this.speakerService.speak("JPMS stands for 'Java Platform Module System'");
27 | this.speakerService.speak("Let's explore it together.");
28 |
29 | this.multipleSpeakerServices.forEach(multipleSpeakerService -> multipleSpeakerService.speak("Multiple services are supported"));
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/samples/basicapplication/application/src/main/java/module-info.java:
--------------------------------------------------------------------------------
1 | import io.github.tomdw.java.modules.spring.samples.basicapplication.internal.MainApplicationConfiguration;
2 | import io.github.tomdw.java.modules.context.boot.api.ModuleContext;
3 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService;
4 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService;
5 |
6 | @ModuleContext(mainConfigurationClass = MainApplicationConfiguration.class)
7 | module io.github.tomdw.java.modules.spring.samples.basicapplication.application {
8 | requires io.github.tomdw.java.modules.spring.samples.basicapplication.speaker;
9 | requires io.github.tomdw.java.modules.context.boot;
10 |
11 | opens io.github.tomdw.java.modules.spring.samples.basicapplication.internal to spring.beans, spring.core, spring.context;
12 |
13 | uses SpeakerService;
14 | uses MultipleSpeakerService;
15 | }
--------------------------------------------------------------------------------
/samples/basicapplication/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 4.0.0
4 |
5 | io.github.tomdw.java.modules
6 | java-modules-parent
7 | 0.0.3
8 |
9 |
10 |
11 | io.github.tomdw.java.modules.spring.samples.basicapplication
12 | basic-application
13 | 0.0.7-SNAPSHOT
14 | pom
15 |
16 |
17 | speaker
18 | application
19 |
20 |
21 |
22 |
23 |
24 | io.github.tomdw.java.modules.spring
25 | java-modules-context-boot-build
26 | ${project.version}
27 | pom
28 | import
29 |
30 |
31 |
32 |
33 |
34 |
35 | org.springframework
36 | spring-context
37 | compile
38 |
39 |
40 | org.springframework
41 | spring-beans
42 | compile
43 |
44 |
45 | org.springframework
46 | spring-core
47 | compile
48 |
49 |
50 | org.junit.jupiter
51 | junit-jupiter
52 |
53 |
54 | org.assertj
55 | assertj-core
56 |
57 |
58 |
--------------------------------------------------------------------------------
/samples/basicapplication/speaker/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | io.github.tomdw.java.modules.spring.samples.basicapplication
5 | basic-application
6 | 0.0.7-SNAPSHOT
7 |
8 | 4.0.0
9 |
10 | speaker
11 |
12 |
13 | io.github.tomdw.java.modules.spring
14 | java-modules-context-boot
15 |
16 |
17 | org.springframework
18 | spring-core
19 |
20 |
21 | org.springframework
22 | spring-beans
23 |
24 |
25 | org.springframework
26 | spring-context
27 |
28 |
29 |
30 |
31 |
32 |
33 | org.codehaus.mojo
34 | exec-maven-plugin
35 |
36 |
37 |
38 |
39 |
40 |
--------------------------------------------------------------------------------
/samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/FailingSpeakerService.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api;
2 |
3 | public interface FailingSpeakerService {
4 |
5 | String getSpeakerNameButThrowsRuntimeException();
6 |
7 | String getSpeakerNameButThrowsCheckedException() throws NoSpeakerCheckedException;
8 | }
9 |
--------------------------------------------------------------------------------
/samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api;
2 |
3 | public interface MultipleSpeakerService {
4 | String getName();
5 | void speak(String message);
6 | }
7 |
--------------------------------------------------------------------------------
/samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerWithGenericsService.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api;
2 |
3 | public interface MultipleSpeakerWithGenericsService {
4 |
5 | T getMultipleSpeakerName();
6 | }
7 |
8 |
--------------------------------------------------------------------------------
/samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NamedSpeakerService.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api;
2 |
3 | public interface NamedSpeakerService {
4 |
5 | String getSpeakerName();
6 |
7 | }
--------------------------------------------------------------------------------
/samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerCheckedException.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api;
2 |
3 | public class NoSpeakerCheckedException extends Exception {
4 | }
5 |
--------------------------------------------------------------------------------
/samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerRuntimeException.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api;
2 |
3 | public class NoSpeakerRuntimeException extends RuntimeException {
4 | }
5 |
--------------------------------------------------------------------------------
/samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api;
2 |
3 | public interface SpeakerService {
4 | String getName();
5 | void speak(String message);
6 | }
7 |
--------------------------------------------------------------------------------
/samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/internal/DefaultFailingSpeakerService.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.internal;
2 |
3 | import javax.inject.Named;
4 |
5 | import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider;
6 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.FailingSpeakerService;
7 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerCheckedException;
8 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerRuntimeException;
9 |
10 | @Named
11 | public class DefaultFailingSpeakerService implements FailingSpeakerService {
12 |
13 | public static FailingSpeakerService provider() {
14 | return provideByInterfaceSoThatADynamicProxyWillBeCreatedWhichShouldNotWrapExceptions();
15 | }
16 |
17 | private static FailingSpeakerService provideByInterfaceSoThatADynamicProxyWillBeCreatedWhichShouldNotWrapExceptions() {
18 | return ModuleServiceProvider.provide(FailingSpeakerService.class);
19 | }
20 |
21 | @Override
22 | public String getSpeakerNameButThrowsRuntimeException() {
23 | throw new NoSpeakerRuntimeException();
24 | }
25 |
26 | @Override
27 | public String getSpeakerNameButThrowsCheckedException() throws NoSpeakerCheckedException {
28 | throw new NoSpeakerCheckedException();
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/internal/DefaultMultipleSpeakerService.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.internal;
2 |
3 | import javax.inject.Named;
4 |
5 | import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider;
6 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService;
7 |
8 | @Named
9 | public class DefaultMultipleSpeakerService implements MultipleSpeakerService {
10 |
11 | public static MultipleSpeakerService provider() {
12 | return ModuleServiceProvider.provide(MultipleSpeakerService.class, "defaultMultipleSpeakerService");
13 | }
14 |
15 | @Override
16 | public String getName() {
17 | return "Default";
18 | }
19 |
20 | @Override
21 | public void speak(String message) {
22 | System.out.println("MULTIPLE - " + message);
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/internal/DefaultMultipleSpeakerWithGenericsService.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.internal;
2 |
3 | import javax.inject.Named;
4 |
5 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerWithGenericsService;
6 |
7 | @Named
8 | public class DefaultMultipleSpeakerWithGenericsService implements MultipleSpeakerWithGenericsService {
9 |
10 | @Override
11 | public String getMultipleSpeakerName() {
12 | return "myMultipleGenericSpeakerName";
13 | }
14 | }
15 |
16 |
--------------------------------------------------------------------------------
/samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/internal/DefaultNamedSpeakerService.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.internal;
2 |
3 | import javax.inject.Named;
4 |
5 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NamedSpeakerService;
6 |
7 | @Named("defaultNamedSpeakerService")
8 | public class DefaultNamedSpeakerService implements NamedSpeakerService {
9 |
10 | @Override
11 | public String getSpeakerName() {
12 | return "defaultNamedSpeakerServiceName";
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/internal/DefaultSpeakerService.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.internal;
2 |
3 | import javax.inject.Named;
4 |
5 | import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider;
6 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService;
7 |
8 | @Named
9 | public class DefaultSpeakerService implements SpeakerService {
10 |
11 | public static SpeakerService provider() {
12 | return ModuleServiceProvider.provide(SpeakerService.class);
13 | }
14 |
15 | @Override
16 | public String getName() {
17 | return "Default";
18 | }
19 |
20 | @Override
21 | public void speak(String message) {
22 | System.out.println("Speaker says: " + message);
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/internal/MultipleSpeakerWithGenericsServiceProvider.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.internal;
2 |
3 | import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider;
4 |
5 | public class MultipleSpeakerWithGenericsServiceProvider {
6 |
7 | public static DefaultMultipleSpeakerWithGenericsService provider() {
8 | return ModuleServiceProvider.provide(DefaultMultipleSpeakerWithGenericsService.class);
9 | }
10 |
11 | }
12 |
--------------------------------------------------------------------------------
/samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/internal/NamedSpeakerServiceProvider.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.internal;
2 |
3 | import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider;
4 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NamedSpeakerService;
5 |
6 | public class NamedSpeakerServiceProvider {
7 | public static NamedSpeakerService provider() {
8 | return ModuleServiceProvider.provide(NamedSpeakerService.class, "otherNamedSpeakerService");
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/internal/OtherMultipleSpeakerService.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.internal;
2 |
3 | import javax.inject.Named;
4 |
5 | import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider;
6 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService;
7 |
8 | @Named
9 | public class OtherMultipleSpeakerService implements MultipleSpeakerService {
10 |
11 | public static MultipleSpeakerService provider() {
12 | return ModuleServiceProvider.provide(MultipleSpeakerService.class, "otherMultipleSpeakerService");
13 | }
14 |
15 | @Override
16 | public String getName() {
17 | return "Other";
18 | }
19 |
20 | @Override
21 | public void speak(String message) {
22 | System.out.println("MULTIPLE OTHER - " + message);
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/internal/OtherNamedSpeakerService.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.internal;
2 |
3 | import javax.inject.Named;
4 |
5 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NamedSpeakerService;
6 |
7 | @Named("otherNamedSpeakerService")
8 | public class OtherNamedSpeakerService implements NamedSpeakerService {
9 |
10 | @Override
11 | public String getSpeakerName() {
12 | return "otherNamedSpeakerServiceName";
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/internal/SpeakerConfiguration.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.internal;
2 |
3 | import org.springframework.context.annotation.ComponentScan;
4 | import org.springframework.context.annotation.Configuration;
5 |
6 | @Configuration
7 | @ComponentScan
8 | public class SpeakerConfiguration {
9 | }
10 |
--------------------------------------------------------------------------------
/samples/basicapplication/speaker/src/main/java/module-info.java:
--------------------------------------------------------------------------------
1 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.FailingSpeakerService;
2 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService;
3 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerWithGenericsService;
4 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NamedSpeakerService;
5 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService;
6 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.internal.DefaultFailingSpeakerService;
7 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.internal.DefaultMultipleSpeakerService;
8 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.internal.MultipleSpeakerWithGenericsServiceProvider;
9 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.internal.NamedSpeakerServiceProvider;
10 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.internal.OtherMultipleSpeakerService;
11 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.internal.SpeakerConfiguration;
12 | import io.github.tomdw.java.modules.context.boot.api.ModuleContext;
13 | import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.internal.DefaultSpeakerService;
14 |
15 | @ModuleContext(mainConfigurationClass = SpeakerConfiguration.class)
16 | module io.github.tomdw.java.modules.spring.samples.basicapplication.speaker {
17 | exports io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api;
18 | requires io.github.tomdw.java.modules.context.boot;
19 |
20 | provides SpeakerService with DefaultSpeakerService;
21 | provides MultipleSpeakerService with DefaultMultipleSpeakerService, OtherMultipleSpeakerService;
22 | provides NamedSpeakerService with NamedSpeakerServiceProvider;
23 | provides MultipleSpeakerWithGenericsService with MultipleSpeakerWithGenericsServiceProvider;
24 | provides FailingSpeakerService with DefaultFailingSpeakerService;
25 |
26 | opens io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.internal to spring.beans, spring.core, spring.context;
27 |
28 | }
--------------------------------------------------------------------------------
/samples/basicapplication/speaker/src/test/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/internal/DefaultSpeakerServiceTest.java:
--------------------------------------------------------------------------------
1 | package io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.internal;
2 |
3 | import org.junit.jupiter.api.Test;
4 |
5 | public class DefaultSpeakerServiceTest {
6 |
7 | @Test
8 | public void canBeConstructed() {
9 | new DefaultSpeakerService();
10 | }
11 |
12 | }
--------------------------------------------------------------------------------
/samples/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | io.github.tomdw.java.modules.spring
5 | java-modules-context-boot-build
6 | 0.0.7-SNAPSHOT
7 |
8 | 4.0.0
9 |
10 | samples
11 | pom
12 |
13 |
14 | basicapplication
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------