├── .gitignore ├── .mvn └── wrapper │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── LICENSE.md ├── README.md ├── mvnw ├── mvnw.cmd ├── pom.xml └── src ├── main └── java │ ├── org │ └── springframework │ │ ├── boot │ │ └── context │ │ │ └── properties │ │ │ ├── VisibleConfigurationPropertiesBinder.java │ │ │ ├── VisibleConversionServiceDeducer.java │ │ │ └── VisiblePropertySourcesDeducer.java │ │ └── data │ │ └── repository │ │ └── config │ │ └── VisibleRepositoryBeanDefinitionBuilder.java │ └── xdb │ └── jpa │ ├── ApplicationContextAwareBinderSupplier.java │ ├── BoundDataSourceRegistrationSupplier.java │ ├── BoundDataSourceSupplier.java │ ├── DataSourceRegistration.java │ ├── DynamicRepositoryConfigurationSourceSupport.java │ ├── EnableMultipleJpaRegistrations.java │ ├── EntityManagerFactorySupplier.java │ ├── JdbcTemplateSupplier.java │ ├── JpaRegistration.java │ ├── JpaRegistrationConfigurer.java │ ├── JpaTransactionManagerSupplier.java │ └── MultipleJpaRegistrationImportBeanDefinitionRegistrar.java └── test └── java └── com └── example └── rds └── RdsApplicationTests.java /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joshlong-attic/multiple-datasource-spring-apps/43e77f3bae6b92d3d9013a9135fc0e126f51031e/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.3/apache-maven-3.5.3-bin.zip 2 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "{}" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright {yyyy} {name of copyright owner} 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Multiple `DataSource` JPA configuration 2 | 3 | This supports easily registering all the required bits for multiple-database JPA use. 4 | 5 | It works with Spring Boot's existing mechanisms for `DataSource` configuration. 6 | 7 | Let's assume you have a freshly generated Spring Boot project from [the Spring Initializr](http://start.spring.io) in 8 | which you've selected a JDBC database driver (in this case, `MySQL`, the example uses MySQL) and Lombok, a compile-time 9 | annotation processor. 10 | 11 | Build this library and add this library (`com.joshlong`:`xdb-jpa`:`0.0.1-SNAPSHOT`) to your application's classpath. 12 | 13 | Let's suppose you have the followng configuration in your Spring Boot `src/main/resources/application.properties`. 14 | These point to real databases on my machine. Configure appropriately and as necessary for your machine. 15 | 16 | ``` 17 | # 18 | # CRM 19 | crm.datasource.url=jdbc:mysql://localhost:3306/crm?useSSL=false 20 | crm.datasource.username=root 21 | crm.datasource.password=root 22 | 23 | # 24 | # BLOG 25 | blog.datasource.url=jdbc:mysql://localhost:3306/blog?useSSL=false 26 | blog.datasource.username=root 27 | blog.datasource.password=root 28 | ``` 29 | 30 | Create the following JPA entities, Spring Data JPA repositories, and database schema. Be careful to put them in two _different_ packages! 31 | 32 | ## The CRM Schema 33 | 34 | 35 | `Order` (under `demo.crm`): 36 | 37 | ``` 38 | package demo.crm; 39 | 40 | import lombok.Data; 41 | 42 | import javax.persistence.Entity; 43 | import javax.persistence.GeneratedValue; 44 | import javax.persistence.Id; 45 | import javax.persistence.Table; 46 | 47 | @Entity 48 | @Table(name = "orders") 49 | @Data 50 | public class Order { 51 | 52 | @Id 53 | @GeneratedValue 54 | private Long id; 55 | private String sku; 56 | } 57 | 58 | ``` 59 | 60 | `Order` maps to a table with roughtly the following DDL: 61 | 62 | ``` 63 | REATE TABLE `orders` ( 64 | `id` bigint(20) NOT NULL, 65 | `sku` varchar(255) DEFAULT NULL, 66 | PRIMARY KEY (`id`) 67 | ) 68 | ``` 69 | 70 | Create the following Spring Data JPA repository: 71 | 72 | ``` 73 | package demo.crm; 74 | 75 | import org.springframework.data.jpa.repository.JpaRepository; 76 | 77 | public interface OrderRepository extends JpaRepository { 78 | } 79 | ``` 80 | 81 | ## The Blog Schema 82 | `Post` (under `demo.blog`): 83 | 84 | ``` 85 | package demo.blog; 86 | 87 | import lombok.Data; 88 | 89 | import javax.persistence.Entity; 90 | import javax.persistence.GeneratedValue; 91 | import javax.persistence.Id; 92 | import javax.persistence.Table; 93 | 94 | @Entity 95 | @Data 96 | @Table(name = "post") 97 | public class Post { 98 | 99 | @Id 100 | @GeneratedValue 101 | private Long id; 102 | private String title; 103 | }; 104 | ``` 105 | 106 | `Post` maps to a table with roughtly the following DDL: 107 | 108 | ``` 109 | CREATE TABLE `post` ( 110 | `id` bigint(20) NOT NULL, 111 | `title` varchar(255) DEFAULT NULL, 112 | PRIMARY KEY (`id`) 113 | ); 114 | ``` 115 | 116 | Create the following Spring Data JPA repository: 117 | 118 | ``` 119 | package demo.blog; 120 | 121 | import org.springframework.data.jpa.repository.JpaRepository; 122 | 123 | public interface PostRepository extends JpaRepository { 124 | } 125 | ``` 126 | 127 | ## The Spring Boot Application 128 | 129 | Create the following Spring Boot main-class (in whatever package you like; I used `demo`). 130 | 131 | ``` 132 | package demo; 133 | 134 | import demo.blog.Post; 135 | import demo.blog.PostRepository; 136 | import demo.crm.Order; 137 | import demo.crm.OrderRepository; 138 | import lombok.extern.log4j.Log4j2; 139 | import org.apache.commons.lang3.builder.ToStringBuilder; 140 | import org.springframework.beans.factory.annotation.Qualifier; 141 | import org.springframework.boot.ApplicationArguments; 142 | import org.springframework.boot.ApplicationRunner; 143 | import org.springframework.boot.SpringApplication; 144 | import org.springframework.boot.autoconfigure.SpringBootApplication; 145 | import org.springframework.context.annotation.Bean; 146 | import org.springframework.jdbc.core.JdbcTemplate; 147 | import org.springframework.orm.jpa.JpaTransactionManager; 148 | import xdb.jpa.DataSourceRegistration; 149 | import xdb.jpa.EnableMultipleJpaRegistrations; 150 | import xdb.jpa.JpaRegistration; 151 | 152 | import javax.persistence.EntityManagerFactory; 153 | import javax.sql.DataSource; 154 | 155 | @SpringBootApplication 156 | @EnableMultipleJpaRegistrations({ 157 | @JpaRegistration(prefix = "crm", rootPackageClass = Order.class), 158 | @JpaRegistration(prefix = "blog", rootPackageClass = Post.class), 159 | }) 160 | @Log4j2 161 | public class DemoApplication { 162 | 163 | public static void main(String args[]) { 164 | SpringApplication.run(DemoApplication.class, args); 165 | } 166 | 167 | private static class LoggingRunner implements ApplicationRunner { 168 | 169 | private final DataSourceRegistration dsr; 170 | private final DataSource ds; 171 | private final JdbcTemplate jt; 172 | private final EntityManagerFactory emf; 173 | private final JpaTransactionManager jtaTxManager; 174 | private final Runnable runnable; 175 | private final String label; 176 | 177 | LoggingRunner(String label, DataSourceRegistration dsr, DataSource ds, JdbcTemplate jt, EntityManagerFactory emf, 178 | JpaTransactionManager jtaTxManager, Runnable runnable) { 179 | this.dsr = dsr; 180 | this.ds = ds; 181 | this.label = label; 182 | this.jt = jt; 183 | this.emf = emf; 184 | this.jtaTxManager = jtaTxManager; 185 | this.runnable = runnable; 186 | } 187 | 188 | @Override 189 | public void run(ApplicationArguments args) throws Exception { 190 | log.info("======================================================================"); 191 | log.info(this.label.toUpperCase() + ':'); 192 | log.info(ToStringBuilder.reflectionToString(dsr)); 193 | log.info(ToStringBuilder.reflectionToString(ds)); 194 | log.info(ToStringBuilder.reflectionToString(jt)); 195 | log.info(ToStringBuilder.reflectionToString(emf)); 196 | log.info(ToStringBuilder.reflectionToString(jtaTxManager)); 197 | runnable.run(); 198 | log.info(System.lineSeparator()); 199 | } 200 | } 201 | 202 | @Bean 203 | ApplicationRunner crmRunner( 204 | @Qualifier("crm") DataSourceRegistration crmDSR, 205 | @Qualifier("crm") DataSource crmDS, 206 | @Qualifier("crm") JdbcTemplate crmJT, 207 | @Qualifier("crm") EntityManagerFactory crmEMF, 208 | @Qualifier("crm") JpaTransactionManager crmTxManager, 209 | OrderRepository or) { 210 | return new LoggingRunner("crm", crmDSR, crmDS, crmJT, crmEMF, crmTxManager, () -> { 211 | crmEMF 212 | .createEntityManager() 213 | .createQuery("select o from " + Order.class.getName() + " o", Order.class) 214 | .getResultList() 215 | .forEach(p -> log.info("order: " + ToStringBuilder.reflectionToString(p))); 216 | or.findAll().forEach(o -> log.info("order (JPA): " + ToStringBuilder.reflectionToString(o))); 217 | }); 218 | } 219 | 220 | @Bean 221 | ApplicationRunner blogRunner( 222 | @Qualifier("blog") DataSourceRegistration blogDSR, 223 | @Qualifier("blog") DataSource blogDS, 224 | @Qualifier("blog") JdbcTemplate blogJT, 225 | @Qualifier("blog") EntityManagerFactory blogEMF, 226 | @Qualifier("blog") JpaTransactionManager blogTxManager, 227 | PostRepository pr) { 228 | return new LoggingRunner("blog", blogDSR, blogDS, blogJT, blogEMF, blogTxManager, () -> { 229 | blogEMF 230 | .createEntityManager() 231 | .createQuery("select b from " + Post.class.getName() + " b", Post.class) 232 | .getResultList() 233 | .forEach(p -> log.info("post: " + ToStringBuilder.reflectionToString(p))); 234 | pr.findAll().forEach(p -> log.info("post (JPA): " + ToStringBuilder.reflectionToString(p))); 235 | }); 236 | } 237 | } 238 | ``` 239 | 240 | What demonstrates is that you now have multiple JPA repositories, databases, and more available for injection in your code. However, as this introduces the possibility of duplicate beans, we need a way to distinguish which instance we want. This library automatically gives every bean a _qualifier_. You can use the Spring `@Qualifier` annotation with the same string as you use for the configuration properties, `crm` and `blog`, in this case. 241 | 242 | Now, you might not want to duplicate that magic string everywhere in your code. And I don't blame you! So create meta annotations, like this: 243 | 244 | ``` 245 | package demo.blog; 246 | 247 | import org.springframework.beans.factory.annotation.Qualifier; 248 | 249 | import java.lang.annotation.*; 250 | 251 | @Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE}) 252 | @Retention(RetentionPolicy.RUNTIME) 253 | @Inherited 254 | @Documented 255 | @Qualifier("blog") 256 | public @interface Blog { 257 | } 258 | ``` 259 | 260 | and 261 | 262 | ``` 263 | package demo.crm; 264 | 265 | import org.springframework.beans.factory.annotation.Qualifier; 266 | 267 | import java.lang.annotation.*; 268 | 269 | @Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE}) 270 | @Retention(RetentionPolicy.RUNTIME) 271 | @Inherited 272 | @Documented 273 | @Qualifier("crm") 274 | public @interface Crm { 275 | } 276 | ``` 277 | 278 | Now, you can replace all uses of `@Qualifier("crm")` with `@Crm` and all uses of `@Qualifier("blog")` with `@Blog`. 279 | 280 | Enjoy! 281 | -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Migwn, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 204 | echo $MAVEN_PROJECTBASEDIR 205 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 206 | 207 | # For Cygwin, switch paths to Windows format before running java 208 | if $cygwin; then 209 | [ -n "$M2_HOME" ] && 210 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 211 | [ -n "$JAVA_HOME" ] && 212 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 213 | [ -n "$CLASSPATH" ] && 214 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 215 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 216 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 217 | fi 218 | 219 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 220 | 221 | exec "$JAVACMD" \ 222 | $MAVEN_OPTS \ 223 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 224 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 225 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 226 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 84 | @REM Fallback to current working directory if not found. 85 | 86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 88 | 89 | set EXEC_DIR=%CD% 90 | set WDIR=%EXEC_DIR% 91 | :findBaseDir 92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 93 | cd .. 94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 95 | set WDIR=%CD% 96 | goto findBaseDir 97 | 98 | :baseDirFound 99 | set MAVEN_PROJECTBASEDIR=%WDIR% 100 | cd "%EXEC_DIR%" 101 | goto endDetectBaseDir 102 | 103 | :baseDirNotFound 104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 105 | cd "%EXEC_DIR%" 106 | 107 | :endDetectBaseDir 108 | 109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 110 | 111 | @setlocal EnableExtensions EnableDelayedExpansion 112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 114 | 115 | :endReadAdditionalConfig 116 | 117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 118 | 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 123 | if ERRORLEVEL 1 goto error 124 | goto end 125 | 126 | :error 127 | set ERROR_CODE=1 128 | 129 | :end 130 | @endlocal & set ERROR_CODE=%ERROR_CODE% 131 | 132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 136 | :skipRcPost 137 | 138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 140 | 141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 142 | 143 | exit /B %ERROR_CODE% 144 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | com.joshlong 6 | xdb-jpa 7 | 0.0.1-SNAPSHOT 8 | jar 9 | 10 | UTF-8 11 | UTF-8 12 | 1.8 13 | 2.0.2.RELEASE 14 | 3.7.0 15 | 16 | 17 | 18 | org.springframework.boot 19 | spring-boot-starter-data-jpa 20 | 21 | 22 | org.projectlombok 23 | lombok 24 | true 25 | 26 | 27 | org.springframework.boot 28 | spring-boot-starter-test 29 | test 30 | 31 | 32 | 33 | 34 | 35 | org.apache.maven.plugins 36 | maven-compiler-plugin 37 | ${maven-compiler-plugin.version} 38 | 39 | ${java.version} 40 | ${java.version} 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | org.springframework.boot 49 | spring-boot-dependencies 50 | ${spring-boot-dependencies.version} 51 | import 52 | pom 53 | 54 | 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/context/properties/VisibleConfigurationPropertiesBinder.java: -------------------------------------------------------------------------------- 1 | package org.springframework.boot.context.properties; 2 | 3 | import org.springframework.context.ApplicationContext; 4 | 5 | /** 6 | * @author Josh Long 7 | */ 8 | public class VisibleConfigurationPropertiesBinder extends ConfigurationPropertiesBinder { 9 | 10 | public VisibleConfigurationPropertiesBinder(ApplicationContext applicationContext, String validatorBeanName) { 11 | super(applicationContext, validatorBeanName); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/context/properties/VisibleConversionServiceDeducer.java: -------------------------------------------------------------------------------- 1 | package org.springframework.boot.context.properties; 2 | 3 | import org.springframework.context.ApplicationContext; 4 | 5 | /** 6 | * @author Josh Long 7 | */ 8 | public class VisibleConversionServiceDeducer extends ConversionServiceDeducer { 9 | 10 | public VisibleConversionServiceDeducer(ApplicationContext applicationContext) { 11 | super(applicationContext); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/context/properties/VisiblePropertySourcesDeducer.java: -------------------------------------------------------------------------------- 1 | package org.springframework.boot.context.properties; 2 | 3 | import org.springframework.context.ApplicationContext; 4 | 5 | /** 6 | * @author Josh Long 7 | */ 8 | public class VisiblePropertySourcesDeducer extends PropertySourcesDeducer { 9 | 10 | public VisiblePropertySourcesDeducer(ApplicationContext applicationContext) { 11 | super(applicationContext); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/data/repository/config/VisibleRepositoryBeanDefinitionBuilder.java: -------------------------------------------------------------------------------- 1 | package org.springframework.data.repository.config; 2 | 3 | import org.springframework.beans.factory.support.BeanDefinitionRegistry; 4 | import org.springframework.core.env.Environment; 5 | import org.springframework.core.io.ResourceLoader; 6 | 7 | /** 8 | * @author Josh Long 9 | */ 10 | public class VisibleRepositoryBeanDefinitionBuilder extends RepositoryBeanDefinitionBuilder { 11 | 12 | public VisibleRepositoryBeanDefinitionBuilder( 13 | BeanDefinitionRegistry registry, 14 | RepositoryConfigurationExtension extension, 15 | ResourceLoader resourceLoader, 16 | Environment environment) { 17 | super(registry, extension, resourceLoader, environment); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/xdb/jpa/ApplicationContextAwareBinderSupplier.java: -------------------------------------------------------------------------------- 1 | package xdb.jpa; 2 | 3 | import org.springframework.beans.PropertyEditorRegistry; 4 | import org.springframework.boot.context.properties.VisibleConversionServiceDeducer; 5 | import org.springframework.boot.context.properties.VisiblePropertySourcesDeducer; 6 | import org.springframework.boot.context.properties.bind.Binder; 7 | import org.springframework.boot.context.properties.bind.PropertySourcesPlaceholdersResolver; 8 | import org.springframework.boot.context.properties.source.ConfigurationPropertySource; 9 | import org.springframework.boot.context.properties.source.ConfigurationPropertySources; 10 | import org.springframework.context.ApplicationContext; 11 | import org.springframework.context.ConfigurableApplicationContext; 12 | import org.springframework.core.convert.ConversionService; 13 | import org.springframework.core.env.PropertySources; 14 | 15 | import java.util.function.Consumer; 16 | import java.util.function.Supplier; 17 | 18 | /** 19 | * @author Josh Long 20 | */ 21 | class ApplicationContextAwareBinderSupplier implements Supplier { 22 | 23 | private Binder binder; 24 | 25 | private final ApplicationContext applicationContext; 26 | 27 | ApplicationContextAwareBinderSupplier(ApplicationContext ac) { 28 | this.applicationContext = ac; 29 | } 30 | 31 | @Override 32 | public Binder get() { 33 | if (null == this.binder) { 34 | this.binder = buildBinder(); 35 | } 36 | return this.binder; 37 | } 38 | 39 | Binder buildBinder() { 40 | PropertySources propertySources = new VisiblePropertySourcesDeducer(this.applicationContext).getPropertySources(); 41 | ConversionService bean = new VisibleConversionServiceDeducer(this.applicationContext).getConversionService(); 42 | Iterable from = ConfigurationPropertySources.from(propertySources); 43 | Consumer editorRegistryConsumer = 44 | ((ConfigurableApplicationContext) this.applicationContext).getBeanFactory()::copyRegisteredEditorsTo; 45 | 46 | return new Binder(from, new PropertySourcesPlaceholdersResolver(propertySources), bean, editorRegistryConsumer); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/xdb/jpa/BoundDataSourceRegistrationSupplier.java: -------------------------------------------------------------------------------- 1 | package xdb.jpa; 2 | 3 | import org.springframework.boot.context.properties.bind.Bindable; 4 | import org.springframework.boot.context.properties.bind.Binder; 5 | import org.springframework.core.ResolvableType; 6 | 7 | import java.util.function.Supplier; 8 | 9 | /** 10 | * @author Josh Long 11 | */ 12 | class BoundDataSourceRegistrationSupplier implements Supplier { 13 | 14 | private final ThreadLocal dsr = new ThreadLocal<>(); 15 | private final String label; 16 | private final Supplier binder; 17 | 18 | BoundDataSourceRegistrationSupplier(Supplier binder, String label) { 19 | this.label = label; 20 | this.binder = binder; 21 | } 22 | 23 | @Override 24 | public DataSourceRegistration get() { 25 | if (this.dsr.get() == null) { 26 | try { 27 | DataSourceRegistration dsr = new DataSourceRegistration(); 28 | dsr.setBeanClassLoader(ClassLoader.getSystemClassLoader()); 29 | dsr.setBeanName(this.label); 30 | this.doBinding(dsr, this.label); 31 | dsr.afterPropertiesSet(); 32 | this.dsr.set(dsr); 33 | } 34 | catch (Exception e) { 35 | throw new RuntimeException(e); 36 | } 37 | } 38 | return this.dsr.get(); 39 | } 40 | 41 | private void doBinding(DataSourceRegistration registration, String prefix) { 42 | ResolvableType resolvableType = ResolvableType.forClass(registration.getClass()); 43 | Bindable target = Bindable 44 | .of(resolvableType) 45 | .withExistingValue(registration); 46 | binder.get().bind(prefix, target, null); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/xdb/jpa/BoundDataSourceSupplier.java: -------------------------------------------------------------------------------- 1 | package xdb.jpa; 2 | 3 | import javax.sql.DataSource; 4 | import java.util.function.Supplier; 5 | 6 | /** 7 | * @author Josh Long 8 | */ 9 | class BoundDataSourceSupplier implements Supplier { 10 | 11 | private final Supplier dataSourceRegistration; 12 | 13 | BoundDataSourceSupplier(Supplier dataSourceRegistration) { 14 | this.dataSourceRegistration = dataSourceRegistration; 15 | } 16 | 17 | @Override 18 | public DataSource get() { 19 | return this.dataSourceRegistration 20 | .get() 21 | .getDataSource() 22 | .initializeDataSourceBuilder() 23 | .build(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/xdb/jpa/DataSourceRegistration.java: -------------------------------------------------------------------------------- 1 | package xdb.jpa; 2 | 3 | import lombok.Data; 4 | import lombok.extern.java.Log; 5 | import org.springframework.beans.factory.BeanClassLoaderAware; 6 | import org.springframework.beans.factory.BeanNameAware; 7 | import org.springframework.beans.factory.InitializingBean; 8 | import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; 9 | import org.springframework.boot.context.properties.NestedConfigurationProperty; 10 | import org.springframework.util.Assert; 11 | 12 | @Log 13 | @Data 14 | public class DataSourceRegistration implements BeanNameAware, BeanClassLoaderAware, InitializingBean { 15 | 16 | @NestedConfigurationProperty 17 | private final DataSourceProperties dataSource; 18 | 19 | private String beanName; 20 | 21 | public DataSourceRegistration() { 22 | this.dataSource = new DataSourceProperties(); 23 | } 24 | 25 | @Override 26 | public void setBeanName(String name) { 27 | this.beanName = name; 28 | } 29 | 30 | public String toString() { 31 | return this.beanName; 32 | } 33 | 34 | @Override 35 | public void setBeanClassLoader(ClassLoader classLoader) { 36 | this.dataSource.setBeanClassLoader(classLoader); 37 | } 38 | 39 | @Override 40 | public void afterPropertiesSet() throws Exception { 41 | this.dataSource.afterPropertiesSet(); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/xdb/jpa/DynamicRepositoryConfigurationSourceSupport.java: -------------------------------------------------------------------------------- 1 | package xdb.jpa; 2 | 3 | import org.springframework.beans.factory.support.BeanDefinitionRegistry; 4 | import org.springframework.core.env.Environment; 5 | import org.springframework.data.repository.config.RepositoryConfigurationSourceSupport; 6 | import org.springframework.data.util.Streamable; 7 | 8 | import java.util.Optional; 9 | 10 | /** 11 | * @author Josh Long 12 | */ 13 | class DynamicRepositoryConfigurationSourceSupport extends RepositoryConfigurationSourceSupport { 14 | 15 | private final String pkg; 16 | private final String transactionManagerRef, entityManagerFactoryRef; 17 | 18 | DynamicRepositoryConfigurationSourceSupport( 19 | Environment environment, 20 | ClassLoader classLoader, 21 | BeanDefinitionRegistry registry, 22 | String pkg, 23 | String transactionManagerBeanName, 24 | String entityManagerFactoryBeanName) { 25 | super(environment, classLoader, registry); 26 | this.transactionManagerRef = transactionManagerBeanName; 27 | this.entityManagerFactoryRef = entityManagerFactoryBeanName; 28 | this.pkg = pkg; 29 | } 30 | 31 | @Override 32 | public Object getSource() { 33 | return null; 34 | } 35 | 36 | @Override 37 | public Streamable getBasePackages() { 38 | return Streamable.of(this.pkg); 39 | } 40 | 41 | @Override 42 | public Optional getQueryLookupStrategyKey() { 43 | return Optional.empty(); 44 | } 45 | 46 | @Override 47 | public Optional getRepositoryImplementationPostfix() { 48 | return Optional.empty(); 49 | } 50 | 51 | @Override 52 | public Optional getNamedQueryLocation() { 53 | return Optional.empty(); 54 | } 55 | 56 | @Override 57 | public Optional getRepositoryBaseClassName() { 58 | return Optional.empty(); 59 | } 60 | 61 | @Override 62 | public Optional getRepositoryFactoryBeanClassName() { 63 | return Optional.empty(); 64 | } 65 | 66 | @Override 67 | public Optional getAttribute(String name) { 68 | 69 | if (name.equalsIgnoreCase("transactionManagerRef")) { 70 | return Optional.of(transactionManagerRef); 71 | } 72 | 73 | if (name.equalsIgnoreCase("entityManagerFactoryRef")) { 74 | return Optional.of(this.entityManagerFactoryRef); 75 | } 76 | 77 | return Optional.empty(); 78 | } 79 | 80 | @Override 81 | public boolean usesExplicitFilters() { 82 | return false; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/xdb/jpa/EnableMultipleJpaRegistrations.java: -------------------------------------------------------------------------------- 1 | package xdb.jpa; 2 | 3 | import org.springframework.context.annotation.Import; 4 | 5 | import java.lang.annotation.*; 6 | 7 | /** 8 | * 9 | * Registers a {@link javax.sql.DataSource}, {@link org.springframework.jdbc.core.JdbcTemplate}, {@link DataSourceRegistration}, 10 | * {@link org.springframework.orm.jpa.JpaTransactionManager}, {@link javax.persistence.EntityManagerFactory}, 11 | * and Spring Data JPA repository support for the specific package. 12 | * 13 | * @author Josh Long 14 | */ 15 | @Target(ElementType.TYPE) 16 | @Retention(RetentionPolicy.RUNTIME) 17 | @Documented 18 | @Inherited 19 | @Import(MultipleJpaRegistrationImportBeanDefinitionRegistrar.class) 20 | public @interface EnableMultipleJpaRegistrations { 21 | JpaRegistration[] value(); 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/xdb/jpa/EntityManagerFactorySupplier.java: -------------------------------------------------------------------------------- 1 | package xdb.jpa; 2 | 3 | import org.springframework.beans.factory.BeanFactory; 4 | import org.springframework.beans.factory.support.DefaultListableBeanFactory; 5 | import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder; 6 | import org.springframework.core.io.ResourceLoader; 7 | import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; 8 | import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; 9 | 10 | import javax.persistence.EntityManagerFactory; 11 | import javax.sql.DataSource; 12 | import java.util.Collections; 13 | import java.util.function.Supplier; 14 | 15 | /** 16 | * @author Josh Long 17 | */ 18 | class EntityManagerFactorySupplier implements Supplier { 19 | 20 | private final DefaultListableBeanFactory registry; 21 | private final ResourceLoader resourceLoader; 22 | private final String dataSourceBeanName; 23 | private final String packageName; 24 | 25 | EntityManagerFactorySupplier(DefaultListableBeanFactory registry, ResourceLoader resourceLoader, String dataSourceBeanName, String packageName) { 26 | this.registry = registry; 27 | this.resourceLoader = resourceLoader; 28 | this.dataSourceBeanName = dataSourceBeanName; 29 | this.packageName = packageName; 30 | } 31 | 32 | LocalContainerEntityManagerFactoryBean createEntityManagerFactoryBean( 33 | BeanFactory registry, 34 | ResourceLoader resourceLoader, 35 | DataSource ds, 36 | String puName, 37 | Package pkg) { 38 | 39 | LocalContainerEntityManagerFactoryBean build = new EntityManagerFactoryBuilder( 40 | new HibernateJpaVendorAdapter(), 41 | Collections.emptyMap(), null) 42 | .dataSource(ds) 43 | .packages(pkg.getName()) 44 | .persistenceUnit(puName) 45 | .build(); 46 | build.setResourceLoader(resourceLoader); 47 | build.setBeanFactory(registry); 48 | build.setBeanClassLoader(ClassLoader.getSystemClassLoader()); 49 | build.afterPropertiesSet(); 50 | return build; 51 | } 52 | 53 | @Override 54 | public EntityManagerFactory get() { 55 | return createEntityManagerFactoryBean( 56 | this.registry, 57 | this.resourceLoader, 58 | this.registry.getBean(dataSourceBeanName, DataSource.class), 59 | this.dataSourceBeanName + "PU", 60 | Package.getPackage(this.packageName)) 61 | .getObject(); 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/xdb/jpa/JdbcTemplateSupplier.java: -------------------------------------------------------------------------------- 1 | package xdb.jpa; 2 | 3 | import org.springframework.beans.factory.support.DefaultListableBeanFactory; 4 | import org.springframework.jdbc.core.JdbcTemplate; 5 | 6 | import javax.sql.DataSource; 7 | import java.util.function.Supplier; 8 | 9 | /** 10 | * @author Josh Long 11 | */ 12 | class JdbcTemplateSupplier implements Supplier { 13 | 14 | private final DefaultListableBeanFactory beanFactory; 15 | private final String beanName; 16 | 17 | JdbcTemplateSupplier(DefaultListableBeanFactory df, String bn) { 18 | this.beanFactory = df; 19 | this.beanName = bn; 20 | } 21 | 22 | @Override 23 | public JdbcTemplate get() { 24 | return new JdbcTemplate(this.beanFactory.getBean(this.beanName, DataSource.class)); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/xdb/jpa/JpaRegistration.java: -------------------------------------------------------------------------------- 1 | package xdb.jpa; 2 | 3 | /** 4 | * Specific information for a given JPA-centric configuration. 5 | * 6 | * @author Josh Long 7 | */ 8 | public @interface JpaRegistration { 9 | 10 | /** 11 | * what Environment configuration property prefix should we apply in looking for the properties to apply 12 | * to a {@link DataSourceRegistration}. 13 | *

14 | * If you used {@code foo}, then this would imply the presence of {@code foo.datasource.url=..}, {@code foo.datasource.password=..}, etc., 15 | * in the Spring Framework {@link org.springframework.core.env.Environment}. 16 | */ 17 | String prefix(); 18 | 19 | /** 20 | * Use to specify the root package against which this JPA configuration should search 21 | */ 22 | String rootPackage() default ""; 23 | 24 | /** 25 | * Use this to specify a type whose package will be used to the exclusion of {@code rootPackage} 26 | */ 27 | Class rootPackageClass() ; 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/xdb/jpa/JpaRegistrationConfigurer.java: -------------------------------------------------------------------------------- 1 | package xdb.jpa; 2 | 3 | import javax.sql.DataSource; 4 | 5 | /** 6 | * @author Josh Long 7 | */ 8 | public interface JpaRegistrationConfigurer { 9 | 10 | DataSource getDataSourceFor(String prefix); 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/xdb/jpa/JpaTransactionManagerSupplier.java: -------------------------------------------------------------------------------- 1 | package xdb.jpa; 2 | 3 | import org.springframework.beans.factory.support.DefaultListableBeanFactory; 4 | import org.springframework.orm.jpa.JpaTransactionManager; 5 | 6 | import javax.persistence.EntityManagerFactory; 7 | import java.util.function.Supplier; 8 | 9 | /** 10 | * @author Josh Long 11 | */ 12 | class JpaTransactionManagerSupplier implements Supplier { 13 | 14 | private final DefaultListableBeanFactory registry; 15 | private final String jpaEntityManagerFactoryBeanName; 16 | 17 | JpaTransactionManagerSupplier(DefaultListableBeanFactory registry, String jpaEntityManagerFactoryBeanName) { 18 | this.jpaEntityManagerFactoryBeanName = jpaEntityManagerFactoryBeanName; 19 | this.registry = registry; 20 | } 21 | 22 | @Override 23 | public JpaTransactionManager get() { 24 | EntityManagerFactory emf = registry.getBean(this.jpaEntityManagerFactoryBeanName, EntityManagerFactory.class); 25 | return new JpaTransactionManager(emf); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/xdb/jpa/MultipleJpaRegistrationImportBeanDefinitionRegistrar.java: -------------------------------------------------------------------------------- 1 | package xdb.jpa; 2 | 3 | import lombok.extern.log4j.Log4j2; 4 | import org.springframework.beans.BeansException; 5 | import org.springframework.beans.factory.annotation.Qualifier; 6 | import org.springframework.beans.factory.config.AutowireCapableBeanFactory; 7 | import org.springframework.beans.factory.config.BeanDefinition; 8 | import org.springframework.beans.factory.support.*; 9 | import org.springframework.boot.context.properties.bind.Binder; 10 | import org.springframework.context.ApplicationContext; 11 | import org.springframework.context.ApplicationContextAware; 12 | import org.springframework.context.EnvironmentAware; 13 | import org.springframework.context.ResourceLoaderAware; 14 | import org.springframework.context.annotation.Configuration; 15 | import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; 16 | import org.springframework.core.annotation.AnnotationAttributes; 17 | import org.springframework.core.env.Environment; 18 | import org.springframework.core.io.ResourceLoader; 19 | import org.springframework.core.type.AnnotationMetadata; 20 | import org.springframework.data.jpa.repository.config.JpaRepositoryConfigExtension; 21 | import org.springframework.data.repository.config.*; 22 | import org.springframework.jdbc.core.JdbcTemplate; 23 | import org.springframework.orm.jpa.JpaTransactionManager; 24 | import org.springframework.transaction.support.TransactionTemplate; 25 | import org.springframework.util.Assert; 26 | import org.springframework.util.StringUtils; 27 | 28 | import javax.persistence.EntityManagerFactory; 29 | import javax.sql.DataSource; 30 | import java.util.function.Supplier; 31 | import java.util.stream.Stream; 32 | 33 | /** 34 | * @author Josh Long 35 | */ 36 | @Log4j2 37 | @Configuration 38 | class MultipleJpaRegistrationImportBeanDefinitionRegistrar implements 39 | ApplicationContextAware, ImportBeanDefinitionRegistrar, EnvironmentAware, ResourceLoaderAware { 40 | 41 | private Environment environment; 42 | private ResourceLoader resourceLoader; 43 | private ApplicationContext applicationContext; 44 | 45 | @Override 46 | public void setEnvironment(Environment environment) { 47 | this.environment = environment; 48 | } 49 | 50 | @Override 51 | public void setResourceLoader(ResourceLoader resourceLoader) { 52 | this.resourceLoader = resourceLoader; 53 | } 54 | 55 | @Override 56 | public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { 57 | this.applicationContext = applicationContext; 58 | } 59 | 60 | @Override 61 | public void registerBeanDefinitions(AnnotationMetadata importingClassAnnotationMetadata, BeanDefinitionRegistry registry) { 62 | 63 | DefaultListableBeanFactory defaultListableBeanFactory = DefaultListableBeanFactory.class.cast(registry); 64 | 65 | if (this.applicationContext == null && registry instanceof AutowireCapableBeanFactory) { 66 | AutowireCapableBeanFactory.class.cast(registry).initializeBean(this, this.getClass().getSimpleName()); 67 | } 68 | 69 | Assert.notNull(this.applicationContext, "the " + ApplicationContext.class.getName() + " reference can't be null!"); 70 | 71 | ApplicationContextAwareBinderSupplier binderSupplier = new ApplicationContextAwareBinderSupplier(this.applicationContext); 72 | 73 | String enableMultipleJpaRegistrationsAnnotationName = EnableMultipleJpaRegistrations.class.getName(); 74 | 75 | importingClassAnnotationMetadata 76 | .getAllAnnotationAttributes(enableMultipleJpaRegistrationsAnnotationName) 77 | .get("value") 78 | .stream() 79 | .map(o -> (AnnotationAttributes[]) o) 80 | .flatMap(Stream::of) 81 | .forEach(jpaRegistration -> { 82 | 83 | String prefix = jpaRegistration.getString("prefix"); 84 | Class rootPackageClass = jpaRegistration.getClass("rootPackageClass"); 85 | String rootPackage = jpaRegistration.getString("rootPackage"); 86 | 87 | String resolvedPackage = (StringUtils.hasText(rootPackage)) ? rootPackage : rootPackageClass.getPackage().getName(); 88 | Assert.hasText(resolvedPackage, "you must specify a root package when using " + enableMultipleJpaRegistrationsAnnotationName); 89 | this 90 | .registerJpaRegistrationsForPrefixAndPackage( 91 | defaultListableBeanFactory, 92 | binderSupplier, 93 | prefix, 94 | resolvedPackage 95 | ); 96 | }); 97 | } 98 | 99 | protected String registerLazyInfrastructureBeanForLabel( 100 | String label, 101 | String newBeanName, 102 | Class clzz, 103 | BeanDefinitionRegistry beanDefinitionRegistry, 104 | Supplier supplier) { 105 | 106 | if (beanDefinitionRegistry.containsBeanDefinition(newBeanName)) { 107 | BeanDefinition beanDefinition = beanDefinitionRegistry.getBeanDefinition(newBeanName); 108 | if (beanDefinition.getBeanClassName().equals(clzz.getName())) { 109 | log.warn(beanDefinitionRegistry.getClass().getName() + " already contains a bean of name '" + 110 | newBeanName + "' of class '" + beanDefinition.getBeanClassName() + "'"); 111 | } 112 | return newBeanName; 113 | } 114 | 115 | GenericBeanDefinition gdb = new GenericBeanDefinition(); 116 | gdb.setBeanClass(clzz); 117 | gdb.setSynthetic(true); 118 | gdb.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); 119 | gdb.setInstanceSupplier(supplier); 120 | gdb.setLazyInit(true); 121 | gdb.addQualifier(new AutowireCandidateQualifier(Qualifier.class, label)); 122 | beanDefinitionRegistry.registerBeanDefinition(newBeanName, gdb); 123 | log.debug("adding qualifier '" + label + "' for " + clzz.getName() + " instance."); 124 | log.debug("registered bean " + newBeanName + "."); 125 | return newBeanName; 126 | } 127 | 128 | 129 | protected void registerJpaRepositories( 130 | String pkg, String transactionManagerBeanName, String entityManagerBeanName, 131 | BeanDefinitionRegistry beanDefinitionRegistry) { 132 | 133 | RepositoryConfigurationSourceSupport configurationSource = new DynamicRepositoryConfigurationSourceSupport( 134 | this.environment, getClass().getClassLoader(), beanDefinitionRegistry, pkg, transactionManagerBeanName, entityManagerBeanName); 135 | 136 | RepositoryConfigurationExtension extension = new JpaRepositoryConfigExtension(); 137 | RepositoryConfigurationUtils.exposeRegistration(extension, beanDefinitionRegistry, configurationSource); 138 | 139 | extension.registerBeansForRoot(beanDefinitionRegistry, configurationSource); 140 | 141 | VisibleRepositoryBeanDefinitionBuilder builder = new VisibleRepositoryBeanDefinitionBuilder(beanDefinitionRegistry, extension, this.resourceLoader, this.environment); 142 | 143 | for (RepositoryConfiguration configuration : extension.getRepositoryConfigurations(configurationSource, resourceLoader, true)) { 144 | 145 | BeanDefinitionBuilder definitionBuilder = builder.build(configuration); 146 | extension.postProcess(definitionBuilder, configurationSource); 147 | definitionBuilder.addPropertyValue("enableDefaultTransactions", false); 148 | 149 | AbstractBeanDefinition beanDefinition = definitionBuilder.getBeanDefinition(); 150 | String beanName = configurationSource.generateBeanName(beanDefinition); 151 | 152 | log 153 | .debug("Spring Data {} - Registering repository: {} - Interface: {} - Factory: {}", 154 | extension.getModuleName(), beanName, configuration.getRepositoryInterface(), configuration.getRepositoryFactoryBeanClassName()); 155 | 156 | beanDefinition.setAttribute("factoryBeanObjectType", configuration.getRepositoryInterface()); 157 | beanDefinitionRegistry.registerBeanDefinition(beanName, beanDefinition); 158 | } 159 | } 160 | 161 | static class JpaRegistrationConfigurerSupplier implements Supplier { 162 | 163 | private final DefaultListableBeanFactory defaultListableBeanFactory; 164 | private final String label; 165 | private final String jpaRegistrationConfigurerBeanName; 166 | 167 | JpaRegistrationConfigurerSupplier(String label, String jparcbn, DefaultListableBeanFactory defaultListableBeanFactory) { 168 | this.defaultListableBeanFactory = defaultListableBeanFactory; 169 | this.jpaRegistrationConfigurerBeanName = jparcbn; 170 | this.label = label; 171 | } 172 | 173 | @Override 174 | public DataSource get() { 175 | 176 | JpaRegistrationConfigurer configurer = this.defaultListableBeanFactory 177 | .getBean(this.jpaRegistrationConfigurerBeanName, JpaRegistrationConfigurer.class); 178 | 179 | return configurer.getDataSourceFor(this.label); 180 | } 181 | } 182 | 183 | protected void registerJpaRegistrationsForPrefixAndPackage( 184 | DefaultListableBeanFactory registry, 185 | Supplier binderSupplier, 186 | String label, 187 | String packageName) { 188 | 189 | BoundDataSourceRegistrationSupplier dsrSupplier = new BoundDataSourceRegistrationSupplier(binderSupplier, label); 190 | 191 | // DataSourceRegistration 192 | this.registerLazyInfrastructureBeanForLabel(label, label + DataSourceRegistration.class.getSimpleName(), DataSourceRegistration.class, registry, dsrSupplier); 193 | 194 | // DataSource 195 | String dataSourceBeanName = label + DataSource.class.getSimpleName(); 196 | 197 | String jpaConfigurerBeanNames[]; 198 | Supplier dataSourceSupplier; 199 | if ((jpaConfigurerBeanNames = registry.getBeanNamesForType(JpaRegistrationConfigurer.class)).length > 0) { 200 | Assert.isTrue(jpaConfigurerBeanNames.length == 1, "there should only be one instance of " + JpaRegistrationConfigurer.class.getName()); 201 | dataSourceSupplier = new JpaRegistrationConfigurerSupplier(label, jpaConfigurerBeanNames[0], registry); 202 | } 203 | else { 204 | dataSourceSupplier = new BoundDataSourceSupplier(dsrSupplier); 205 | } 206 | this.registerLazyInfrastructureBeanForLabel(label, dataSourceBeanName, DataSource.class, registry, dataSourceSupplier); 207 | 208 | // JdbcTemplate 209 | this.registerLazyInfrastructureBeanForLabel(label, label + JdbcTemplate.class.getSimpleName(), JdbcTemplate.class, registry, new JdbcTemplateSupplier(registry, dataSourceBeanName)); 210 | 211 | // JPA EntityManagerFactory 212 | EntityManagerFactorySupplier emfSupplier = new EntityManagerFactorySupplier(registry, this.resourceLoader, dataSourceBeanName, packageName); 213 | Class entityManagerFactoryClass = EntityManagerFactory.class; 214 | String jpaEntityManagerFactoryBeanName = label + entityManagerFactoryClass.getSimpleName(); 215 | this.registerLazyInfrastructureBeanForLabel(label, jpaEntityManagerFactoryBeanName, entityManagerFactoryClass, registry, emfSupplier); 216 | 217 | // JPA TransactionManager 218 | JpaTransactionManagerSupplier jpaTransactionManagerSupplier = new JpaTransactionManagerSupplier(registry, jpaEntityManagerFactoryBeanName); 219 | String jpaTransactionManagerBeanName = label + JpaTransactionManager.class.getName(); 220 | this.registerLazyInfrastructureBeanForLabel(label, jpaTransactionManagerBeanName, JpaTransactionManager.class, registry, jpaTransactionManagerSupplier); 221 | 222 | // JPA TransactionTemplate 223 | this.registerLazyInfrastructureBeanForLabel(label, label + TransactionTemplate.class.getSimpleName(), 224 | TransactionTemplate.class, registry, () -> new TransactionTemplate( 225 | registry.getBean(jpaTransactionManagerBeanName, JpaTransactionManager.class) 226 | )); 227 | 228 | // Spring Data JPA 229 | this.registerJpaRepositories(packageName, jpaTransactionManagerBeanName, jpaEntityManagerFactoryBeanName, registry); 230 | } 231 | } 232 | -------------------------------------------------------------------------------- /src/test/java/com/example/rds/RdsApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.rds; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class RdsApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | --------------------------------------------------------------------------------