I am learning Spring Boot and in my first set up I got this problem:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured
I looked up solutions on the web and did find some, including those from Stackoverflow, but none of them works.
My simple code:
#SpringBootApplication
#RestController
public class SpringBootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootDemoApplication.class, args);
}
#RequestMapping(value = "/")
public String response(){
return "You made it!";
}
}
My POM:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
My application.properties:
spring.datasource.url=jdbc:mysql://localhost:3306/hrdb?autoReconnect=true
spring.datasource.username=root
spring.datasource.password=passw0rd
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
I also created a file as the following:
#Configuration
public class DBConfig {
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/hr?autoReconnect=true");
dataSource.setUsername("root");
dataSource.setPassword("passw0rd");
return dataSource;
}
}
I got the mentioned error either in Unit Test or starting the service. The only way I find out to make it work is to disable data source auto config:
#SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
Need your help. Thanks.
Check your DB config - it seems to overwrite Spring's default data source, but the url is different than in application.properties: "jdbc:mysql://localhost:3306/hr?autoReconnect=true"
In the properties you have:
"jdbc:mysql://localhost:3306/hrdb?autoReconnect=true"
"hr" vs "hrdb".
I would get rid of this class altogether and instead declare the relevant JDBC driver in your pom.xml and let Spring take care of the connection.
Related
I'm facing issue with Swagger Integration in Spring Boot. Have a look at the code and error snippet.
------------------POM--------------------
<properties>
<java.version>1.8</java.version>
<swagger.version>2.9.2</swagger.version>
</properties>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-bean-validators</artifactId>
<version>${swagger.version}</version>
</dependency>
-----------------App class--------------
#SpringBootApplication
#EnableSwagger2
public class ProducerApplication {
public static void main(String[] args) {
SpringApplication.run(ServletPocProducerApplication.class, args);
}
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
Stack Trace
org.springframework.context.ApplicationContextException: Failed to start bean
'documentationPluginsBootstrapper'; nested exception is
java.lang.NullPointerException: Cannot invoke
"org.springframework.web.servlet.mvc.condition.PatternsRequestCondition.toString()"
because the return value of
"springfox.documentation.spi.service.contexts.Orderings.patternsCondition(springfox.docume
ntation.RequestHandler)" is null
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:181) ~[spring-context-5.3.13.jar:5.3.13]
How do I fix this??
I solved it by adding "spring.mvc.pathmatch.matching-strategy=ant-path-matcher" in application.properties.
For a long time I have tried to solve this problem and solution for this is:
a) adding this to application.properties:
spring.mvc.pathmatch.matching-strategy=ant-path-matcher
b) adding this to application.yaml(or application.yml):
spring:
mvc:
pathmatch:
matching-strategy: ant_path_matcher
I know this does not solve your problem directly, but consider moving to springdoc. Springfox is so buggy at this point that is a pain to use. I've moved to springdoc 2 years ago because of its Spring WebFlux support and I am very happy about it. Additionally, it also supports Kotlin Coroutines, which I am not sure Springfox does.
If you decide to migrate, springdoc even has a migration guide.
For the integration between spring-boot and swagger-ui, add the library to the list of your project dependencies (No additional configuration is needed):
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.5.12</version>
</dependency>
The Swagger UI page will then be available at
http://server:port/context-path/swagger-ui.html and the OpenAPI
description will be available at the following url for json format:
http://server:port/context-path/v3/api-docs
server: The server name or IP
port: The server port
context-path: The context path of the application
Adding this "spring.mvc.pathmatch.matching-strategy=ant-path-matcher" to your application.properties file solves the problem.
It's what i used and i saved me alot of trouble.
My suggestion is when you are using spring-boot then it is better to use spring boot dependency for swagger. So, spring-boot will take care of your default settings.
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>...</version>
</dependency>
I'm trying to start my spring-boot-web app but I'm getting the following error :
2020-03-17 20:54:22.643 WARN 15640 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.
2020-03-17 20:54:22.664 ERROR 15640 --- [ main] o.s.boot.SpringApplication : Application run failed
I configured the following ApplicationContext file :
#Configuration
#EnableJpaRepositories(basePackages = {"repos"})
public class AppConfig {
#Bean
public LocalEntityManagerFactoryBean entityManagerFactory() {
LocalEntityManagerFactoryBean factoryBean = new LocalEntityManagerFactoryBean();
factoryBean.setPersistenceUnitName("mydb");
return factoryBean;
}
#Bean
public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
}
I need those beans because in one of my services I inject the following objects :
#Autowired
private EntityManagerFactory emf;
#PersistenceContext
private EntityManager em;
and my main app :
#SpringBootApplication
public class Application extends SpringBootServletInitializer {
public static void main(String[]args)
{
//load the spring config class we configured
SpringApplication.run(AppConfig.class);
}
my dependencies in pom.xml :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.1.Final</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.11</version>
</dependency>
Solutions I tried but didnt work :
1)add extends SpringBootServletInitializer to both Application.java and Appconfig.java
2)Move the beans from the AppConfig.java to Application.java
3)Tried to set the following annotation on the application class :
#SpringBootApplication(exclude = {DataSourceAutoConfiguration.class })
4)Adding the following dependency to the pom.xml :
org.springframework.boot
spring-boot-starter-tomcat
2.2.5.RELEASE
I resolved my problem by adding dependancy 'spring-boot-starter-web'.
Make sure that your filename, class name and the name of the class inside the SpringApplication.run() function are the same.
Also, make sure you haven't forgotten the #SpringBootApplication annotation.
My solution :
In addition to the persistence.xml file I created application.properties file :
# Connection url for the database
spring.datasource.url=jdbc:postgresql://ip:port/db
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.hibernate.ddl-auto =update
spring.jpa.show-sql = true
chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQL9Dialect
spring.jpa.generate-ddl=true
server.port = 9091
Afterwards, in my Application.java I added the following annotations and extend :
#SpringBootApplication
#EnableJpaRepositories("repositories")
#EntityScan("dao")
public class Application extends SpringBootServletInitializer {
You can comment the <scope>provided</scope> in pom.xml file like below
You need to override configure method from SpringBootServletInitializer
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
I have the following error coming up:
Exception: Error creating bean with name 'inventoryService' defined in URL [jar:file:/app.jar!/BOOT-INF/classes!/com/epi/services/inventory/items/InventoryService.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'itemRepository': Cannot resolve reference to bean 'databaseClient' while setting bean property 'databaseClient'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'databaseClient' available
2019-06-18 18:38:41,409 INFO [main] org.apache.juli.logging.DirectJDKLog: Stopping service [Tomcat]
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.apache.catalina.loader.WebappClassLoaderBase (jar:file:/app.jar!/BOOT-INF/lib/tomcat-embed-core-8.5.29.jar!/) to field java.lang.Thread.threadLocals
WARNING: Please consider reporting this to the maintainers of org.apache.catalina.loader.WebappClassLoaderBase
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
2019-06-18 18:38:45,424 INFO [main] org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener:
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-06-18 18:38:50,695 ERROR [main] org.springframework.boot.diagnostics.LoggingFailureAnalysisReporter:
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in com.epi.services.inventory.items.InventoryService required a bean named 'databaseClient' that could not be found.
Action:
Consider defining a bean named 'databaseClient' in your configuration.
My application has the following classes and dependencies:
Inside main module:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-r2dbc</artifactId>
</dependency>
<dependency>
<groupId>io.r2dbc</groupId>
<artifactId>r2dbc-postgresql</artifactId>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
</dependency>
<dependency>
<groupId>myGroupId</groupId>
<artifactId>myModule.dblib</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.projectreactor</groupId>
<artifactId>reactor-spring</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
</dependency>
</dependencies>
App:
#SpringBootApplication(scanBasePackages = "com.pack")
#EntityScan("com.pack")
#EnableR2dbcRepositories
#Import(DatabaseConfiguration.class)
public class InventoryApplication {
public static void main(String[] args) {
SpringApplication.run(InventoryApplication.class, args);
}
}
Service:
#Service
#RequiredArgsConstructor
public class InventoryService {
private final ItemRepository itemRepository;
public Flux<ItemPojo> getAllItems() {
return itemRepository.findAllItems()
.map(Item::toPojo);
}
}
Repo:
#Repository
public interface ItemRepository extends ReactiveCrudRepository<Item, Long> {
Flux<List<Item>> findByName(String name);
#Query("select i from Item i")
Flux<Item> findAllItems();
}
Entity:
#Data
#Table(name = "items")
public class Item implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
public static ItemPojo toPojo(final Item items) {
return new ItemPojo(items.id, items.name);
}
}
myModule.dblib:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-r2dbc</artifactId>
</dependency>
<dependency>
<groupId>io.r2dbc</groupId>
<artifactId>r2dbc-postgresql</artifactId>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-r2dbc</artifactId>
</dependency>
<dependency>
<groupId>io.r2dbc</groupId>
<artifactId>r2dbc-postgresql</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.projectreactor</groupId>
<artifactId>reactor-spring</artifactId>
</dependency>
</dependencies>
Database config:
#Configuration
#EnableR2dbcRepositories
public class DatabaseConfiguration {
#Value("${spring.data.postgres.host}") private String host;
#Value("${spring.data.postgres.port}") private int port;
#Value("${spring.data.postgres.database}") private String database;
#Value("${spring.data.postgres.username}") private String username;
#Value("${spring.data.postgres.password}") private String password;
#Bean
public PostgresqlConnectionFactory connectionFactory() {
return new PostgresqlConnectionFactory(PostgresqlConnectionConfiguration.builder()
.host(host)
.port(port)
.database(database)
.username(username)
.password(password)
.build());
}
}
What am I missing?
im going to shamelessly plug my own article about how to get started with R2DBC postgres and spring boot.
R2DBC getting started
I think your problem lies in how you initiate your database connectionFactory. According to the documentation you need to extend and override the AbstractR2dbcConfiguration#connectionFactory
#Configuration
#EnableR2dbcRepositories
public class PostgresConfig extends AbstractR2dbcConfiguration {
#Override
#Bean
public ConnectionFactory connectionFactory() {
return new PostgresqlConnectionFactory(
PostgresqlConnectionConfiguration.builder()
.host("localhost")
.port(5432)
.username("postgres")
.password("mysecretpassword")
.database("myDatabase")
.build());
}
}
Official documentation
This approach lets you use the standard io.r2dbc.spi.ConnectionFactory instance, with the container using Spring’s AbstractR2dbcConfiguration.
As compared to registering a ConnectionFactory instance directly, the configuration support has the added advantage of also providing the container with an ExceptionTranslator implementation that translates R2DBC exceptions to exceptions in Spring’s portable DataAccessException hierarchy for data access classes annotated with the #Repository annotation.
This hierarchy and the use of #Repository is described in Spring’s DAO support features.
AbstractR2dbcConfiguration registers also DatabaseClient that is required for database interaction and for Repository implementation.
Official R2DBC documentation
Turns out I needed to have my Database configuration class extend AbstractR2dbcConfiguration which includes the DatabaseClient bean.
From a TDD approach, I worked from trying to get the following TestNG method to work:
#Test
#Slf4j
#SpringBootTest
class PostgresSanityTesting extends AbstractTestNGSpringContextTests{
#Autowired
DatabaseClient databaseClient
void sanityCheck() {
assert databaseClient
}
But to get there, there's some work...
First, I'm not seeing any effective code unless I forced my gradle subproject to build with
ext['spring.version'] = '5.2.0.M2'
which in fact is called out in the R2Dbc documentation. And half of the other dependencies are coming in from spring experimental and milestones. So "buyer beware"... (e.g. I'm still not seeing R2dbc correctly handle repository save(), and a series of other problems.)
As to the instant coding problem:
Given the correct set up, the database client is a #Bean configured as part of the AbstractR2dbcConfiguration class, and then that TestNg test will pass.
But I found that I needed to still create a #Bean, and I inject the connection factory parameters via #ConfigurationProperties. I separate those concerns in two files, as placing the #Bean in with the subclass of AbstractR2dbcConfiguration just didn't work for me.
Here's the code I'm using, expressed in groovy.
import io.r2dbc.spi.ConnectionFactory
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Profile
import org.springframework.data.r2dbc.config.AbstractR2dbcConfiguration
import org.springframework.data.r2dbc.repository.config.EnableR2dbcRepositories
#Configuration
class R2DbcConfiguration extends AbstractR2dbcConfiguration {
private final ConnectionFactory connectionFactory
R2DbcConfiguration( ConnectionFactory connectionFactory ) {
this.connectionFactory = connectionFactory
}
#Override
ConnectionFactory connectionFactory() {
this.connectionFactory
}
}
and
import io.r2dbc.postgresql.PostgresqlConnectionConfiguration
import io.r2dbc.postgresql.PostgresqlConnectionFactory
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Profile
#Configuration
#EnableConfigurationProperties
#ConfigurationProperties(prefix = "spring.datasource")
class PostgresConnectionConfig{
String database
String username
String password
String host
String port
#Bean
PostgresqlConnectionFactory connectionFactory() {
final def dbPort = port as Integer
PostgresqlConnectionConfiguration config = PostgresqlConnectionConfiguration.builder() //
.host(host)
.port(dbPort)
.database(database)
.username(username)
.password(password).build()
PostgresqlConnectionFactory candidate = new PostgresqlConnectionFactory(config)
candidate
}
}
and part of my application.yml
spring:
datasource:
url: jdbc:postgresql://127.0.0.1:5432/postgres
driver-class-name: org.postgresql.Driver
driverClassName: org.postgresql.Driver
database: postgres
host: localhost
port: 5432
password: pokey0
username: postgres
and excerpts from my subproject's build.gradle
repositories {
maven { url "https://repo.spring.io/libs-milestone" }
}
dependencies {
implementation group: 'org.springframework.data', name: 'spring-data-releasetrain', version: 'Lovelace-RELEASE', ext: 'pom'
implementation group: 'org.springframework.data', name: 'spring-data-r2dbc', version: '1.0.0.M2'
implementation group: 'io.r2dbc', name: 'r2dbc-postgresql', version: '1.0.0.M7'
implementation('org.springframework.boot:spring-boot-starter-webflux')
implementation('io.projectreactor:reactor-test')
implementation group: 'org.postgresql', name: 'postgresql', version: '42.2.5'
implementation('org.springframework.boot:spring-boot-starter-actuator')
testImplementation('org.springframework.boot:spring-boot-starter-test')
implementation group: 'javax.persistence', name: 'javax.persistence-api', version: '2.2'
}
I'm writing a Spring Boot application which connects with Snowflake Data Warehouse and execute SQL queries on it.
I have written a Configuration class for configuring Datasource for connecting to Snowflake Data Warehouse as follows:
#Configuration
#EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class DBConfig {
Logger logger = LoggerFactory.getLogger(DBConfig.class);
#Bean
JdbcTemplate jdbcTemplate() throws IllegalAccessException, InvocationTargetException, InstantiationException {
logger.info("-----Configuring JDBCTemplate------");
SnowflakeBasicDataSource dataSource = new SnowflakeBasicDataSource();
dataSource.setServerName("<myserver>.snowflakecomputing.com");
dataSource.setUser("<my_username>");
dataSource.setPassword("<my_password>");
dataSource.setWarehouse("DEMO_WH");
dataSource.setDatabaseName("DEMO_DB");
dataSource.setSchema("PUBLIC");
return new JdbcTemplate(dataSource);
}
}
My pom.xml looks like as follows:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.vaibhav</groupId>
<artifactId>snowflake-1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>snowflake-1</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>net.snowflake</groupId>
<artifactId>snowflake-jdbc</artifactId>
<version>3.6.21</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
I have to use a connection pool for this data source in my Spring boot application.
How can I use HikariCP connection pool in my application which can work perfectly fine with my Customized DataSource?
------EDIT --- Thanks for providing solution, finally my working code looks like
#Configuration
#EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class })
public class DBConfig {
Logger logger = LoggerFactory.getLogger(DBConfig.class);
#Bean
JdbcTemplate jdbcTemplate() throws IllegalAccessException, InvocationTargetException, InstantiationException {
logger.info("-----Configuring JDBCTemplate------");
HikariConfig config = new HikariConfig();
config.setDriverClassName("net.snowflake.client.jdbc.SnowflakeDriver");
// config.setDataSourceProperties(properties);
config.setJdbcUrl("jdbc:snowflake://<myserver>.snowflakecomputing.com/?warehouse=DEMO_WH&db=DEMO_DB&schema=PUBLIC");
config.setUsername("<my_username>");
config.setPassword("<my_password>");
HikariDataSource ds = new HikariDataSource(config);
return new JdbcTemplate(ds);
}
}
See setting SnowflakeDriver with Hikari:
HikariConfig config = new HikariConfig();
config.setDriverClassName("com.snowflake.client.jdbc.SnowflakeDriver");
config.setDataSourceProperties(properties);
config.setJdbcUrl(connectStr);
HikariDataSource ds = new HikariDataSource(config);
If spring-jdbc is being included, Spring will automatically create JdbcTemplate based on the available DataSource. So If the above answers does not satisfy you, you may just try:
#Configuration
#EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class DBConfig {
Logger logger = LoggerFactory.getLogger(DBConfig.class);
// TAKE NOTE THAT THIS MIGHT ALREADY BE DONE BY SPRING
#Bean
protected JdbcTemplate jdbcTemplate( DataSource dataSource )
{
return new JdbcTemplate( dataSource );
}
#Bean
protected DataSource makeDataSource() throws IllegalAccessException, InvocationTargetException, InstantiationException {
logger.info("-----Configuring JDBCTemplate------");
SnowflakeBasicDataSource dataSource = new SnowflakeBasicDataSource();
dataSource.setServerName("<myserver>.snowflakecomputing.com");
dataSource.setUser("<my_username>");
dataSource.setPassword("<my_password>");
dataSource.setWarehouse("DEMO_WH");
dataSource.setDatabaseName("DEMO_DB");
dataSource.setSchema("PUBLIC");
return dataSource;
}
}
Hikari is default connection pool in Spring-boot 2+
We have nothing to do if we want to use Hikari in an application based
on Spring Boot 2.x.
You can set different properties of connection pool thru application.yml / application.properties. Below is an example of application.yml:
spring:
datasource
hikari:
maximumPoolSize: 4 # Specify maximum pool size
minimumIdle: 1 # Specify minimum pool size
driver-class-name: com.snowflake.client.jdbc.SnowflakeDriver
This is a useful link for configuring Hikari CP.
Dependencies
org.springframework.cloud:spring-cloud-starter-feign:jar:1.2.2.RELEASE:compile
com.netflix.feign:feign-core:jar:8.16.2:compile
com.netflix.feign:feign-slf4j:jar:8.16.2:compile
com.netflix.feign:feign-jackson:jar:8.15.1:compile
Enabling Feign on SpringBootAppilication
#EnableFeignClients(basePackages = "com.vett.services.bucket.restclient")
Feign interface Client
#FeignClient(name = "myClient", configuration = ClientConfigs.class, url = "https://my-endpoint");
public interface MyClient {
Results in this error
org.springframework.core.annotation.AnnotationConfigurationException: Attribute 'value' in annotation [org.springframework.cloud.netflix.feign.FeignClient] must be declared as an #AliasFor [serviceId], not [name]
So far I have
As its unclear to me what the issue is i have used the value instead of name, my searching has not been successful i have see a few issues with feign annotation but not appear to be similar to this at all
I was getting the same issue, Once I added the below dependency , it started working :
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:Brixton.SR7"}
}
I am using Spring boot 1.4 but Spring 4.3.6. Also Spring feign 1.2.5.RELEASE
This error may occur when using multiple feign clients or bad package architecture. Sometimes this error occurs due to version incompatibilities, but in some projects we may not be able to change the versions. Therefore, you can solve the problem with the following codes. This codes worked for me.
Use this annotation in ApplicationStarter class:
#EnableFeignClients
Feign Client Interface:
import org.springframework.cloud.netflix.feign.FeignClient;
#FeignClient(value = "account-service", url = "${feign.client.account-service}", path = "/account/api/v1")
public interface AccountServiceClient {
#RequestLine("POST /customer/{email}/?name={accountName}")
Long registerCustomer(#Param("email") String email, #Param("accountName") String accountName);
}
Define bean for multiple feign usage:
#Bean
#Qualifier("account-feign-client")
public AccountServiceClient accountServiceClient() {
return Feign.builder().target( AccountServiceClient.class,"${feign.client.account-service}");
}
#Bean
#Qualifier("mail-feign-client")
public MailServiceClient mailServiceClient() {
return Feign.builder().target( MailServiceClient.class,"${feign.client.mail-service}");
}
Autowire in service:
#Autowired
#Qualifier("account-feign-client")
private AccountServiceClient accountServiceClient;
pom.xml:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring.boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Brixton.SR7</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
<version>1.4.7.RELEASE</version>
</dependency>
...
</dependencies>