#ConditionalOnProperty not working when building jar locally although it is working fine when getting included from remote repo - maven

To be more specific in the below code if I am providing only the property of MongoDB(spring.data.mongodb) in application.yml it is throwing RunTime exception stating that
PostgresDBPurgeController bean can not be created missing spring.datasource
but as per #ConditionalOnProperty if the property is not there Bean creation would not happen.
In detail,I have the below code in a common jar and I have 2 different app(1 use postgres as db ,another mongo as db ) which use this same jar and both the apps are working fine when I am including the jar from remote repo.
But when I build the common jar locally and and run the app (which use mongo as db ) locally it is throwing above error.
#ConditionalOnProperty(prefix = "spring.data.mongodb", name = "host")
#ConditionalOnProperty(prefix = "spring.datasource", name = "driver-class-name", havingValue = "org.postgresql.Driver")
public class PostgresDBPurgeController {

Related

Spring Boot not able to pick value from yml file

I have a application-local.yml file inside resources folder. I have some properties like
data: https://xyzw/
I am using this property in a different class
#Service
public class Test {
#Value("${data}")
private String data;
}
When I run the Application.java I get the following error:
Application.main(Application.java:13), exception_class=org.springframework.beans.factory.BeanCreationException, exception_message=Error creating bean with name 'Test': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'data' in value "${data}"}","threadID":"main","sourceHost":"H18NPLFI13P0303","logVersion":"1.5","category":"org.springframework.boot.SpringApplication"}
Which is weird. I am not sure why it's not picking the values from the application-local.yml file.
If you start your application with IntelliJ IDEA and want the application-local.yml properties to be used, you need to edit your run configuration so that the local profile is used, else the application-local.yml properties won't be picked up by Spring.

jar with embedded tomcat, when using another spring project, is not working with just yml - it's needing a blank application.properties file as well

Been searching for others that have run into this issue, and not finding much out there, so it can't be that common.
I have a spring-boot project that I want to convert into a jar project, running with embedded tomcat. It's using yml files (application.yml and then the profile versions - eg appplication-dev.yml.) It ran fine as war with the yml files, however, when I convert it to a jar, and kick off the jar, the embedded tomcat never starts UNLESSS I add an empty application.properties file as well. (No errors just no Tomcat startup unless the empty application.properties file is added.)
I believe it's somehow related to one of our internal jar dependencies (also spring), since if I remove that dependency from the pom (and any of the code referencing it) I can get the jar to startup the embedded tomcat just fine (without providing the empty application.properties file.)
I could also, of course, forgo using yml files and just use .properties files, but I'd like to use yml files if possible. Why adding an empty applcation.properties file causes things to work has me stumped.
If it helps, the config in the dependency project that causes the issue we're seeing is set up as:
#Configuration
#EnableConfigurationProperties(OracleDataSourceProperties.class)
#EnableTransactionManagement
#ComponentScan(basePackages = {"com.foo.data.services","com.foo.data.domain", "com.foo.utility", "com.foo.cipher.utility"})
#MapperScan(value = {"com.foo.data.services.mapper","com.foo.data.services.batchmapper"})
public class DataServicesPersistenceConfig { ... }
and the OracleDataSourceProperties class:
#ConfigurationProperties(prefix="oradb", ignoreUnknownFields = true)
public class OracleDataSourceProperties extends BaseVO implements InitializingBean{

Running 'mvn clean install' on Spring Boot application using env variables in application.properties

Hello I am trying to package my Spring Boot app into a jar.
I want to deploy this app to AWS Beanstalk and so I will be injecting some variables into application.properties using Environment variables.
spring.data.mongodb.uri=${MONGODB_URI}
spring.data.mongodb.auto-index-creation=true
spring.servlet.multipart.max-file-size=-1
spring.servlet.multipart.max-request-size=-1
CLOUDINARY_URL=${CLOUDINARY_URL}
jwt-secret=${JWT_SECRET}
server.port=5000
However when I run the maven command (mvn clean install), during the package process the code is executed and it is failing stating that
BeanCreationException: Error creating bean with name 'customBeansConfig': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'CLOUDINARY_URL' in value "${CLOUDINARY_URL}"
I have a class CustomBeansConfig:
#Configuration
public class CustomBeansConfig {
#Value("${CLOUDINARY_URL}")
private String cloudinaryUrl;
#Bean
public Cloudinary cloudinary(){
System.out.println("cloudinaryUrl = " + cloudinaryUrl);
return new Cloudinary(cloudinaryUrl);
}
}
Please help me to create the jar file
If I have understood you correctly, one approach may be to use different application.properties files for different environments. For example application-dev.properties for the Dev environment and application-prod.properties for the Prod environment. Then your CLOUDINARY_URL may be assigned different literal values appropriate to each.
Then when deploying to each environment, bundle your JAR with the -Denv option, as in
mvn -Denv=dev clean install
OR
mvn -Denv=prod clean install
... and upload the resulting JAR file to the corresponding AWS environment.
Running the Spring Boot application with a such config property, got me the following error:
Caused by: java.lang.IllegalArgumentException: Circular placeholder reference 'CLOUDINARY_URL' in property definitions
Changing the name of your Spring property from CLOUDINARY_URL to, for example, cloudinary.service.url will resolve the issue.
In such case, your config file should look like this:
spring.data.mongodb.uri=${MONGODB_URI}
spring.data.mongodb.auto-index-creation=true
spring.servlet.multipart.max-file-size=-1
spring.servlet.multipart.max-request-size=-1
cloudinary.service.url=${CLOUDINARY_URL}
jwt-secret=${JWT_SECRET}
server.port=5000
And your configuration file like this:
#Configuration
public class CustomBeansConfig {
#Value("${cloudinary.service.url}")
private String cloudinaryUrl;
#Bean
public Cloudinary cloudinary(){
System.out.println("cloudinaryUrl = " + cloudinaryUrl);
return new Cloudinary(cloudinaryUrl);
}
}
Also, I would advise you to avoid creating Spring configuration properties using the underscore format, since it usually used for the environment variables, maybe be confusing and may cause such interesting issues.

Spring boot: populate h2 db from schema in test/resources

On my local machine I load an in-memory h2 database to start my spring boot application in a safe environment, here's the properties:
spring.datasource.url: jdbc:h2:mem:DB_TEST;Mode=Oracle
spring.datasource.platform: h2
spring.jpa.hibernate.ddl-auto: none
spring.datasource.continue-on-error: false
spring.jpa.database-platform: org.hibernate.dialect.Oracle10gDialect
Then, in my src/main/resources I have the file schema-h2.sql containing my local db initiations.
That's fine, but then I also have some junit tests I want to execute:
#RunWith(SpringRunner.class)
#SpringBootTest
public class MyTest {
#Autowired
private MyController controller;
#Test
public void myTest(){
controller.doSomething();
}
This is also fine, as the schema-h2.sql is seen.
Anyway according to me it would be better to put the schema-h2.sql in src/test/resources as it has to be used only on my local environment. Doing so also allows maven to exclude it from the final build and that is also pretty fine.
Anyway if I put it there the test keeps working...but the main application breaks as the schema-h2.sql is not found!
How to modify the above properties to specify that the shema-h2.sql has to be searched inside of the test/resources folder?
Thanks
For normal mode, the properties file is put in src/main/resources,
and for the testing method, the properties file in the src/test/resources folder.
By Trying to run a test-class, eclipse runs EACH file ending with .sql (and thus containing a script to create tables or to insert data) it finds under src/main/resources and src/test/resources.
So if you put a script-file schema.sql (containing a script that creates a table: create table ..) in both folders, you'll get an "table already exits" error, if you let jut one, the test will run smoothly.
If you put a script-file (that insert data in a table) in both folder, both scripts will be run.
You can also use the #PropertySource("..") in your repository to tell spring where to find the properties-file to use.

Spring boot on Tomcat with external configuration

I can't find an answer to this question on stackoverflow hence im asking here so I could get some ideas.
I have a Spring Boot application that I have deployed as a war package on Tomcat 8. I followed this guide Create a deployable war file which seems to work just fine.
However the issue I am currently having is being able to externalize the configuration so I can manage the configuration as puppet templates.
In the project what I have is,
src/main/resources
-- config/application.yml
-- config/application.dev.yml
-- config/application.prod.yml
-- logback-spring.yml
So how can I possibly load config/application.dev.yml and config/application.prod.yml externally and still keep config/application.yml ? (contains default properties including spring.application.name)
I have read that the configuration is load in this order,
A /config subdirectory of the current directory.
The current directory
A classpath /config package
The classpath root
Hence I tried to load the configuration files from /opt/apache-tomcat/lib to no avail.
What worked so far
Loading via export CATALINA_OPTS="-Dspring.config.location=/opt/apache-tomcat/lib/application.dev.yml"
however what I would like to know is,
Find out why loading via /opt/apache-tomcat/lib classpath doesn't work.
And is there a better method to achieve this ?
You are correct about load order. According to Spring boot documentation
SpringApplication will load properties from application.properties files in the following locations and add them to the Spring Environment:
A /config subdirectory of the current directory.
The current directory
A classpath /config package
The classpath root
The list is ordered by precedence (properties defined in locations higher in the list override those defined in lower locations).
[Note]
You can also use YAML ('.yml') files as an alternative to '.properties'.
This means that if you place your application.yml file to /opt/apache-tomcat/lib or /opt/apache-tomcat/lib/config it will get loaded.
Find out why loading via /opt/apache-tomcat/lib classpath doesn't work.
However, if you place application.dev.yml to that path, it will not be loaded because application.dev.yml is not filename Spring is looking for. If you want Spring to read that file as well, you need to give it as option
--spring.config.name=application.dev or -Dspring.config.name=application.dev.
But I do not suggest this method.
And is there a better method to achieve this ?
Yes. Use Spring profile-specific properties. You can rename your files from application.dev.yml to application-dev.yml, and give -Dspring.profiles.active=dev option. Spring will read both application-dev.yml and application.yml files, and profile specific configuration will overwrite default configuration.
I would suggest adding -Dspring.profiles.active=dev (or prod) to CATALINA_OPTS on each corresponding server/tomcat instance.
I have finally simplified solution for reading custom properties from external location i.e outside of the spring boot project. Please refer to below steps.
Note: This Solution created and executed windows.Few commands and folders naming convention may vary if you are deploying application on other operating system like Linux..etc.
1. Create a folder in suitable drive.
eg: D:/boot-ext-config
2. Create a .properties file in above created folder with relevant property key/values and name it as you wish.I created dev.properties for testing purpose.
eg :D:/boot-ext-config/dev.properties
sample values:
dev.hostname=www.example.com
3. Create a java class in your application as below
------------------------------------------------------
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
#PropertySource("classpath:dev.properties")
#ConfigurationProperties("dev")
public class ConfigProperties {
private String hostname;
//setters and getters
}
--------------------------------------------
4. Add #EnableConfigurationProperties(ConfigProperties.class) to SpringBootApplication as below
--------------------------------------------
#SpringBootApplication
#EnableConfigurationProperties(ConfigProperties.class)
public class RestClientApplication {
public static void main(String[] args) {
SpringApplication.run(RestClientApplication.class, args);
}
}
---------------------------------------------------------
5. In Controller classes we can inject the instance using #Autowired and fetch properties
#Autowired
private ConfigProperties configProperties;
and access properties using getter method
System.out.println("**********hostName******+configProperties.getHostName());
Build your spring boot maven project and run the below command to start application.
-> set SPRING_CONFIG_LOCATION=<path to your properties file>
->java -jar app-name.jar

Resources