Updated Question based upon feedback:
I have a spring-boot application that has three databases: H2 for integration testing, and Postgresql for qa & production. Since spring-boot creates a default datasource for you, I don't have anything defined for my integration tests. I thought I would use application.properties to define my datasource connection values but I am not certain what is the best way to handle this.
I have two files:
src/main/resources/application.properties
spring.profiles.active=production
appName = myProduct
serverPort=9001
spring.datasource.url=jdbc:postgresql://localhost/myDatabase
spring.datasource.username=user
spring.datasource.password=password
spring.datasource.driverClassName=org.postgresql.Driver
spring.jpa.hibernate.hbm2ddl.auto=update
spring.jpa.hibernate.ejb.naming_strategy=org.hibernate.cfg.EJB3NamingStrategy
spring.jpa.hibernate.show_sql=true
spring.jpa.hibernate.format_sql=true
spring.jpa.hibernate.use_sql_comments=false
spring.jpa.hibernate.type=all
spring.jpa.hibernate.disableConnectionTracking=true
spring.jpa.hibernate.default_schema=dental
src/main/resources/application-test.properties
spring.profiles.active=test
serverPort=9002
spring.datasource.url = jdbc:h2:~/testdb
spring.datasource.username = sa
spring.datasource.password =
spring.datasource.driverClassName = org.h2.Driver
liquibase.changeLog=classpath:/db/changelog/db.changelog-master.sql
I used to run my tests with with gradle (using "gradle build test") or within IntelliJ. I updated my gradle file to use:
task setTestEnv {
run { systemProperty "spring.profiles.active", "test" }
}
But when I run gradle clean build setTestEnv test I get errors that seem to indicate the test is trying to connect to an actual Postgresql database:
Caused by: org.postgresql.util.PSQLException: Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:138)
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:66)
at org.postgresql.jdbc2.AbstractJdbc2Connection.<init>(AbstractJdbc2Connection.java:125)
at org.postgresql.jdbc3.AbstractJdbc3Connection.<init>(AbstractJdbc3Connection.java:30)
at org.postgresql.jdbc3g.AbstractJdbc3gConnection.<init>(AbstractJdbc3gConnection.java:22)
at org.postgresql.jdbc4.AbstractJdbc4Connection.<init>(AbstractJdbc4Connection.java:32)
at org.postgresql.jdbc4.Jdbc4Connection.<init>(Jdbc4Connection.java:24)
at org.postgresql.Driver.makeConnection(Driver.java:393)
at org.postgresql.Driver.connect(Driver.java:267)
at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:278)
at org.apache.tomcat.jdbc.pool.PooledConnection.connect(PooledConnection.java:182)
at org.apache.tomcat.jdbc.pool.ConnectionPool.createConnection(ConnectionPool.java:701)
at org.apache.tomcat.jdbc.pool.ConnectionPool.borrowConnection(ConnectionPool.java:635)
at org.apache.tomcat.jdbc.pool.ConnectionPool.init(ConnectionPool.java:486)
at org.apache.tomcat.jdbc.pool.ConnectionPool.<init>(ConnectionPool.java:144)
at org.apache.tomcat.jdbc.pool.DataSourceProxy.pCreatePool(DataSourceProxy.java:116)
at org.apache.tomcat.jdbc.pool.DataSourceProxy.createPool(DataSourceProxy.java:103)
at org.apache.tomcat.jdbc.pool.DataSourceProxy.getConnection(DataSourceProxy.java:127)
at liquibase.integration.spring.SpringLiquibase.afterPropertiesSet(SpringLiquibase.java:288)
... 42 more
Caused by: java.net.ConnectException: Connection refused
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
I haven't figured out how to set the default system.property == "test" within IntelliJ yet...
See section 21.3 of the Spring Boot documentation. This section describes how to define profile specific property files that use the format application-{profile}.properties. This can help you isolate properties on a per profile basis.
You can annotate your tests adding #ActiveProfiles in the following way:
#SpringApplicationConfiguration(classes = {Application.class, TestSpringConfiguration.class})
#Test(groups = "integration")
#ActiveProfiles("test")
public class MyServiceTest extends AbstractTransactionalTestNGSpringContextTests {
...
#Test
public void testSomething() {
...
}
}
I'm using TestNG but JUnint wouldn't be much different.
You can also specify additional configuration as showed in the example above.
That way you won't need to set the profile in build.gradle or launch configuration in IntelliJ
Related
SpringBoot 2.7.1 with Spring Cloud Config
I have a test
#ActiveProfiles({"local","h2dbmem"})
#SpringBootTest(properties = {"server.ssl.enabled=false"})
#AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
#TestPropertySource(locations = "classpath:application-integrationtest.properties")
public class SystemTest {
...
}
and I then run Maven to run the test :
mvn -Dspring.profiles.include=cloudconfig clean verify
When the test runs, the console says :
The following 3 profiles are active: "cloudconfig", "local", "h2dbmem"
Although this is exactly what I wanted, that it ends up using the JDBC URL and credentials from the h2dbmem profile and not the JDBC URL and credentials from the cloud-config profile, I could not find documentation on why cloudconfig ( supplied via command-line ) was added as the first entry in the list of active profiles after the profiles supplied via the #ActiveProfiles annotation.
To be honest, I was actually expecting the following order of profiles :
The following 3 profiles are active: "local", "h2dbmem", "cloudconfig"
... where the JDBC URL and credentials from cloudconfig are used, but I am glad it was not.
So question is:
Is there specific documentation on the sequence / order of profiles when they are supplied in multiple ways ( annotation, command-line, etc ) ?
Note I am aware of the order and sequence / preference of properties, which is not what I am asking.
I have an application.properties file in Spring Boot v2.6.1 where I declared a multi document file notation like below :
spring.profiles.active=#spring.profiles.active#
#---
spring.config.activate.on-profile=prod
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.Oracle12cDialect
#---
spring.config.activate.on-profile=dev
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
This works perfectly fine(i.e., picked accordingly) when I run the application in integrated server or IDE by passing spring.profiles.active as prod/dev in VM Arguments.
The same thing doesn't work when I deploy as a war in tomcat by passing in setenv.sh as
export CATALINA_OPTS="$CATALINA_OPTS -Dspring.profiles.active=prod"
it always picks the "org.hibernate.dialect.MySQL8Dialect" instead of "org.hibernate.dialect.Oracle12cDialect"
Any help?
After a day of brain storming, finally I found the solution to pick the respective dialect when using multiple datasources based on the profile.
In my case, Primary datasource is Oracle with UCP and secondary is mySQL for Prod & dev profiles respectively.
As per the question, multi document file notation in application.properties works fine in IDE or integrated tomcat but not in External tomcat when deployed as a WAR.
Below solution works for both (Integrated & External Tomcat)
In MySQL Configuration class, I have set the custom JPA Properties as a tweak.
#Configuration
#Profile(someConstants.ENV_DEV)
public class MySqlConfiguration {
private static final Logger logger = LogManager.getLogger(MySqlConfiguration.class);
#Bean(name = "mySQL")
#Profile(someConstants.ENV_DEV)
#ConfigurationProperties(prefix = "spring.mysql.datasource")
public DataSource dataSource() {
final String METHOD_NAME = ":: DataSource ::";
logger.info(METHOD_NAME + "Initialising the MySQL Connection");
return DataSourceBuilder.create().build();
}
#Bean
#ConfigurationProperties(prefix = "spring.mysql.jpa")
public JpaProperties jpaProperties() {
JpaProperties properties = new JpaProperties();
return properties;
}
}
In Application.properties
spring.mysql.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect // this for mySQL
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.Oracle12cDialect // this for Oracle
Moreover, I have done the same setting in setenv.sh file for external tomcat
// for prod
export CATALINA_OPTS="$CATALINA_OPTS -Dspring.profiles.active=prod"
// for dev
#export CATALINA_OPTS="$CATALINA_OPTS -Dspring.profiles.active=dev"
I analysed the logs and now each datasources picks up the respective properties & dialect based on profile, perfectly fine and awesome.
Happy Coding..
There are several ways present to define "active profiles" for a Spring Boot application.
The default one is to pass it through a command line, like this:
java -Dspring.profiles.active=dev,local -jar myapp.jar
it works just fine (as expected): All three sets of profile-related properties will be loaded in proper order:
application.yaml
application-dev.yaml will override the previous one
application-local.yaml will override the previous one as well (these properties will have the most priority)
Based on the idea, that my "local" profile should always "use and overrides" properties from the "dev", let's "hardcode" such behavior.
Let's use the 'spring.profiles.include' feature for this. So, the following lines are added to the 'application-local.yaml':
spring.profiles:
include:
- dev
I expect, now I can pass the "local" profile only in the command line, and the "dev" profile will be applied automatically (with his properties, of course):
java -Dspring.profiles.active=local -jar myapp.jar
But ooop!*: properties from the 'application-dev.yaml' are ignored.
Why? Is it a bug? Is it a feature that forces me to list all profiles in a command line directly?
I'm sure that the behavior around profiles activation should be the same without any difference in how the active-profiles list was passed to Spring Boot framework.
The application:
#SpringBootApplication #EnableConfigurationProperties( MyProps::class )
class SpringApp4
#ConfigurationProperties("my.db") #ConstructorBinding
data class MyProps(val name: String, val url: String, val user: String)
#Component
class MyRunner(val myProps: MyProps, val env: Environment) : CommandLineRunner {
override fun run(vararg args: String) {
println("myProps = $myProps")
println("activeProfiles = ${env.activeProfiles.joinToString()}")
exitProcess(0)
}
}
fun main() { runApplication<SpringApp4>() }
application.yaml:
my.db:
name: "default-name"
url: "default-url"
user: "default-user"
application-dev.yaml:
my.db:
url: "dev-url"
user: "dev-user"
application-local.yaml:
spring.profiles.include:
- dev
my.db:
user: "local-user"
Run1: java -Dspring.profiles.active=dev,local -jar myapp.jar
Correct output:
myProps = MyProps(name=default-name, url=dev-url, user=local-user)
activeProfiles = dev, local
it's correct because the url=dev-url
Run2: java -Dspring.profiles.active=local -jar myapp.jar
Incorrect output:
myProps = MyProps(name=default-name, url=default-url, user=local-user)
activeProfiles = local
It's not correct because the url=default-url and the activeProfiles doesn't contain the "dev" at all.
Help me please to figure out how to use the spring.profiles.include feature in yaml to build a kind of top level profiles that will activate other automatically.
In Run2 You are giving profile as local
i.e
-Dspring.profiles.active=local
So spring will first load application.yml and then application-local.yml
I can see the output is expected.
Since some properties like name and url are not present in application-local.yml, so the values of these fields will be same as present in application.yml
FYI : application.yml is always called irrespective of profile, and then it gets overridden by the profile mentioned in -Dspring.profiles.active property
spring.profiles.include deprecated in Spring Boot 2.4 and no longer works: https://spring.io/blog/2020/08/14/config-file-processing-in-spring-boot-2-4
It caused recursive resource loading; that broke Kubernates ConfigMap so they removed recursion.
Use spring.profiles.active or spring.profiles.group.
It's my first time implementing a Spring application using Spring Cloud Config framework. The application is working fine, getting configuration properties from repository through the server application. So, at the moment I must write the integration tests to test connection between client application and server and repository. To do it I mean get a value from repository over properties and check the value, also make a request to the server, or if exists, other method inside spring cloud config library to make it.
The problem now, when executing the integrationTest the application can't read the properties from remote. I've created a bootstrap.yml on the integrationTest context but not works. So, I got the errors like: Could not resolve placeholder.
MyIntegrationTest
#RunWith(SpringJUnit4ClassRunner.class)
#SpringBootTest()
#ActiveProfiles("integrationTest")
public class MyIntegrationTest {
#Value("${throttling.request.rate.minute}")
private int MAX_REQUEST_PER_MINUTE;
#Test
public void validateGetRequestRateLimitFromRepository() {
Assert.assertNotEquals(MAX_REQUEST_PER_MINUTE,1L);
}
}
bootstrap.yml
spring:
application:
name: sample-name
---
spring:
profiles: local #also tried integrationTest
cloud:
config:
enabled: true
uri: https://endpoint-uri:443
skipSslValidation: true
name: ${spring.application.name},${spring.application.name}-${spring.profiles}
Also tried:
Set application-integrationTest.yml
Set application.yml
Set bootstrap-integrationTest.yml
Create a *-integrationTest.yml at the repo.
Set #ActiveProfiles("local") on integrationTest class.
Nothing works.
I am trying to test a grails app connecting to a sql server, for now, I am using one of my own. This is my datasource.groovy
dataSource {
configClass = GrailsAnnotationConfiguration.class
pooled = true
driverClassName = "oracle.jdbc.driver.OracleDriver"
dialect = "org.hibernate.dialect.Oracle10gDialect"
dbCreate = "update" // one of 'create', 'create-drop', 'update', 'validate', ''
url = "jdbc:oracle:thin:#127.0.0.1:1521/xe"
username = "blah"
password = "blah"
properties {
validationQuery="select 1 from dual"
testWhileIdle=true
timeBetweenEvictionRunsMillis=60000
}
}
I have borrowed this code from a different app, just changing the url and user/password. The other app runs fine, but my app throws a long exception, which boils down to this
Caused by SQLNestedException: Cannot load JDBC driver class 'oracle.jdbc.driver.OracleDriver'
stack trace
Caused by ClassNotFoundException: oracle.jdbc.driver.OracleDriver
I have copied ojdbc6.jar into my app lib/ but I am afraid I am lost on what to do next.
EDIT I have updated oracle.jdbc.driver.OracleDriver to oracle.jdbc.OracleDriver, but no progress
Run
grails compile --refresh-dependencies
when you add a jar to the lib directory so Grails adds it to the classpath. This is a new requirement in 2.0+
Unrelated - you can remove
configClass = GrailsAnnotationConfiguration.class
since that's the default now
Shouldn't the class be:
driverClassName = "oracle.jdbc.OracleDriver"
I believe the other one was deprecated
So, turns out the problem was what #tim_yates suggested. The problem that I had since then was that even though I was refreshing the dependencies, as #burt said, but I had never re-loaded the config files.
I just ran grails clean then grails compile --refresh-dependencies and voila, problem solved. Thanks to #burt and #tim_yates for helping me out