Issue with application.properties file in java - java

I am trying to fetch the database values from properties, so for the same reason I am using #PropertySource in spring, but it is throwing the FileNotFoundException
#Configuration
#EnableJpaRepositories(basePackages = {
"com.manju.springdata.repository"
})
#EnableTransactionManagement
#EnableWebMvc
#ComponentScan(basePackages = "com.manju.springdata.*")
#PropertySource("classpath:/application.properties")
public class PersistenceContext {
#Value("${db.driver}")
private String dbDriver;
#Value("${db.url}")
private String dbURL;
#Value("${db.username}")
private String dbUserName;
#Value("${db.password}")
private String dbPassword;
#Bean(destroyMethod = "close")
DataSource dataSource(Environment env){
BoneCPDataSource dataSource = new BoneCPDataSource();
//dataSource.setDriverClass(env.getRequiredProperty("db.driver"));
dataSource.setDriverClass(dbDriver);
dataSource.setJdbcUrl(dbURL);
dataSource.setUsername(dbUserName);
dataSource.setPassword(dbPassword);
return dataSource;
}
#Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
My project structure is as follows,
I am getting the following error,
Caused by: java.io.FileNotFoundException: class path resource [application.properties] cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:172) ~[spring-core-4.2.0.RELEASE.jar:4.2.0.RELEASE]
at org.springframework.core.io.support.EncodedResource.getInputStream(EncodedResource.java:153) ~[spring-core-4.2.0.RELEASE.jar:4.2.0.RELEASE]
at org.springframework.core.io.support.PropertiesLoaderUtils.fillProperties(PropertiesLoaderUtils.java:98) ~[spring-core-4.2.0.RELEASE.jar:4.2.0.RELEASE]
at org.springframework.core.io.support.PropertiesLoaderUtils.fillProperties(PropertiesLoaderUtils.java:72) ~[spring-core-4.2.0.RELEASE.jar:4.2.0.RELEASE]
at org.springframework.core.io.support.PropertiesLoaderUtils.loadProperties(PropertiesLoaderUtils.java:58) ~[spring-core-4.2.0.RELEASE.jar:4.2.0.RELEASE]
at org.springframework.core.io.support.ResourcePropertySource.<init>(ResourcePropertySource.java:84) ~[spring-core-4.2.0.RELEASE.jar:4.2.0.RELEASE]
at org.springframework.context.annotation.ConfigurationClassParser.processPropertySource(ConfigurationClassParser.java:360) ~[spring-context-4.2.0.RELEASE.jar:4.2.0.RELEASE]
at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:254) ~[spring-context-4.2.0.RELEASE.jar:4.2.0.RELEASE]
at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:231) ~[spring-context-4.2.0.RELEASE.jar:4.2.0.RELEASE]
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:198) ~[spring-context-4.2.0.RELEASE.jar:4.2.0.RELEASE]
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:167) ~[spring-context-4.2.0.RELEASE.jar:4.2.0.RELEASE]
... 57 common frames omitted
How do I access my properties file values, what's wrong with my code? Any suggestions

The problem is with your folder structure. The resource folder should be under main, not java. Look at this for default structure of maven project.
Either move the resource folder or change value to classpath:/resources/application.properties.

Related

DataSource failing to instantiate

I am trying to connect to an external mssql database but I am getting a bean instantiation exception. I have tried annotating my main class with #EnableJpaRepo, excluding DataSourceAutoConfiguration etc. I tried using myBatis and it worked but I've been instructed to use Jpa. Thank you.
My .yml file:
ansir.datasource:
schema: schema
jdbc-url: jdbc:sqlserver://SERVER:PORTNO;databaseName=DB;encrypt=false
username: root
password: pwd
driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
hikari.maximum-pool-size: 10
hikari.pool-name: HikariPool-ANSIR
jpa:
show-sql: true
hibernate.dialect: org.hibernate.dialect.SQLServer2012Dialect
hibernate.ddl-auto: none
my config class:
#Value("${ansir.datasource}")
private String SCHEMA_NAME;
#Value("${ansir.datasource.jdbc-url}")
private String jdbcUrl;
#Value("${ansir.datasource.username}")
private String username;
#Value("${ansir.datasource.password}")
private String password;
#Value("${ansir.datasource.driver-class-name}")
private String driverClassName;
#Value("${ansir.datasource.hikari.maximum-pool-size}")
private String maxPool;
#Value("${ansir.datasource.hikari.pool-name}")
private String poolName;
#Value("${ansir.datasource.jpa.show-sql}")
private String showSql;
#Value("${ansir.datasource.jpa.hibernate.dialect}")
private String hibernateDialect;
#Value("${ansir.datasource.jpa.hibernate.ddl-auto}")
private String ddl;
private final Environment env;
#Autowired
public ANSIRConfiguration(Environment env) {
this.env = env;
}
#Bean
#ConfigurationProperties("ansir.datasource")
public DataSource ansirDataSource() {
return DataSourceBuilder.create()
.driverClassName(env.getProperty(driverClassName))
.url(env.getProperty(jdbcUrl))
.username(env.getProperty(username))
.password(env.getProperty(password))
.build();
}
#Bean
public PlatformTransactionManager ansirTransactionManager(#Qualifier("ansirEntityManager") LocalContainerEntityManagerFactoryBean entityManagerFactoryBean) {
JpaTransactionManager transactionManager
= new JpaTransactionManager();
transactionManager.setEntityManagerFactory(
entityManagerFactoryBean.getObject());
return transactionManager;
}
#Bean("ansirEntityManager")
public LocalContainerEntityManagerFactoryBean ansirEntityManager(#Qualifier("ansirDataSource")DataSource ansirDataSource) {
LocalContainerEntityManagerFactoryBean entityManagerFactory
= new LocalContainerEntityManagerFactoryBean();
entityManagerFactory.setDataSource(ansirDataSource);
entityManagerFactory.setPackagesToScan("com.autonation.ca.client.ansir.entity");
entityManagerFactory.setPersistenceUnitName("ansir");
HibernateJpaVendorAdapter vendorAdapter
= new HibernateJpaVendorAdapter();
entityManagerFactory.setJpaVendorAdapter(vendorAdapter);
HashMap<String, Object> properties = new HashMap<>();
properties.put("hibernate.hbm2ddl.auto",
env.getProperty(ddl));
properties.put("hibernate.dialect",
env.getProperty(hibernateDialect));
properties.put("hibernate.proc.param_null_passing", true);
properties.put("hibernate.show_sq", showSql);
entityManagerFactory.setJpaPropertyMap(properties);
return entityManagerFactory;
}
}
my stack trace:
Caused by: java.lang.NullPointerException: null
at java.base/java.util.concurrent.ConcurrentHashMap.putVal(ConcurrentHashMap.java:1011)
at java.base/java.util.concurrent.ConcurrentHashMap.putIfAbsent(ConcurrentHashMap.java:1541)
at java.base/java.lang.ClassLoader.getClassLoadingLock(ClassLoader.java:667)
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(BuiltinClassLoader.java:591)
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:579)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
at com.zaxxer.hikari.HikariConfig.attemptFromContextLoader(HikariConfig.java:970)
at com.zaxxer.hikari.HikariConfig.setDriverClassName(HikariConfig.java:480)
at org.springframework.boot.jdbc.DataSourceBuilder$MappedDataSourceProperty.set(DataSourceBuilder.java:460)
at org.springframework.boot.jdbc.DataSourceBuilder$MappedDataSourceProperties.set(DataSourceBuilder.java:355)
at org.springframework.boot.jdbc.DataSourceBuilder.build(DataSourceBuilder.java:190)
at com.autonation.ca.client.ansir.config.ANSIRConfiguration.ansirDataSource(ANSIRConfiguration.java:64)
at com.autonation.ca.client.ansir.config.ANSIRConfiguration$$EnhancerBySpringCGLIB$$307494cc.CGLIB$ansirDataSource$2()
at com.autonation.ca.client.ansir.config.ANSIRConfiguration$$EnhancerBySpringCGLIB$$307494cc$$FastClassBySpringCGLIB$$d0e3b4d8.invoke()
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:331)
at com.autonation.ca.client.ansir.config.ANSIRConfiguration$$EnhancerBySpringCGLIB$$307494cc.ansirDataSource()
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
Thank you.
change application.yml file to application.properties with these config,
ansir.datasource.schema= schema
ansir.datasource.jdbc-url=jdbc:sqlserver://SERVER;databaseName=DB;encrypt=false
ansir.datasource.username=root
ansir.datasource.password=pwd
ansir.datasource.driver-class-name= com.microsoft.sqlserver.jdbc.SQLServerDriver
ansir.datasource.hikari.maximum-pool-size=10
ansir.datasource.hikari.pool-name= HikariPool-ANSIR
ansir.datasource.jpa.show-sql= true
ansir.datasource.jpa.hibernate.dialect= org.hibernate.dialect.SQLServer2012Dialect
ansir.datasource.jpa.hibernate.ddl-auto= none
period is not normal use in application.yml file.

Spring confiuration reading incorrect value from the properties file while creating JDBC connection

I have a Spring Configuration bean which looks like this
#Configuration
#PropertySource("classpath:db/jdbc2.properties")
public class DbConfig {
#Value("${driverClassName}")
private String driverClassName;
#Value("${url}")
private String url;
#Value("${username}")
private String username;
#Value("${password}")
private String password;
#Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
#SuppressWarnings("unchecked")
#Lazy
#Bean
public DataSource dataSource() {
try {
SimpleDriverDataSource dataSource = new SimpleDriverDataSource();
Class<? extends Driver> driver = (Class<? extends Driver>) Class.forName(driverClassName);
dataSource.setDriverClass(driver);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
} catch (Exception e) {
return null;
}
}
}
The jdbc2.properties file looks like this
driverClassName=com.mysql.cj.jdbc.Driver
#url=jdbc:mysql://localhost:3306/musicdb?useSSL=true
url=jdbc:mysql://localhost:3306/musicdb
username=prospring6
password=prospring6
However, when I run try to get JDBC connection, I get the following error
java.sql.SQLException: Access denied for user 'Delta'#'localhost' (using password: YES)
Even though, username field is set prospring6 in the properties file, the configuration is reading it as Delta, which is my system's username.
If you are using windows then might be this is the issue.
https://docs.oracle.com/javase/tutorial/essential/environment/env.html
(See the platform dependency issue section)
Changed the property key from username to db.username (it should be anything but not only username)... might be it will starts working.

How to create database table with spring boot after change the data source URL

I use spring-boot with DATAJPA repository and two datasource. One datasource connect to a MySQL DB and the 2nd to a file based embedded H2 DB.
On the H2 DB i want change the URL during my application ist running. The URL changing work and after change the URL to an not existing DB spring create the DB. But the tables will not create and spring give me an error like Table "SYMBOL" not found; SQL statement:.
When i restart my app now then spring create the tables with the new URL and everything work fine.
How i can create the tables after change the URL?
To change the URL i write my own datasource and build it new on each connection.
public class ProjectDataSource extends AbstractDataSource {
#Autowired ToolService toolService;
#Override
public Connection getConnection() throws SQLException {
return determineTargetDataSource().getConnection();
}
#Override
public Connection getConnection(String username, String password) throws SQLException {
return determineTargetDataSource().getConnection(username, password);
}
#ConfigurationProperties(prefix = "project.datasource")
private DataSource determineTargetDataSource() {
String projectName = toolService.get().getProjectName();
String url = "jdbc:h2:file:../db/" + projectName;
return DataSourceBuilder
.create()
.url(url)
.build();
}
}
Here the configuration
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(
entityManagerFactoryRef = "projectEntityManagerFactory",
transactionManagerRef = "projectTransactionManager",
basePackages = {"at.ltw.test.bz.model.project"})
public class ProjectDbConfiguration {
#Bean(name = "projectDataSource")
public DataSource dataSource() {
return new ProjectDataSource();
}
#Bean(name = "projectEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean
barEntityManagerFactory(
EntityManagerFactoryBuilder builder,
#Qualifier("projectDataSource") DataSource dataSource
) {
HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
jpaVendorAdapter.setGenerateDdl(true);
return builder
.dataSource(dataSource)
.packages("at.ltw.test.bz.model.project")
.persistenceUnit("bzProject")
.properties(jpaVendorAdapter.getJpaPropertyMap())
.build();
}
#Bean(name = "projectTransactionManager")
public PlatformTransactionManager barTransactionManager(
#Qualifier("projectEntityManagerFactory") EntityManagerFactory projectEntityManagerFactory) {
return new JpaTransactionManager(projectEntityManagerFactory);
}
}
Here my application.properties
#jpa
spring.jpa.hibernate.ddl-auto=update
spring.jpa.generate-ddl=true
#tool database
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost/ltw?useSSL=false
spring.datasource.username=ltw
spring.datasource.password=password
#project database
project.datasource.driver-class-name=org.h2.Driver
#logging
logging.level.at.ltw = trace
Hope somebody can help me and sorry for my bad English ...
JPA Will not help you because it is only at init state that DDL are checked.
You need to use something like flywayDB or liquibase or simple SQL file to generate the new DB.
Anyway, you code is wrong, and I'm surprise you don't have error.
#Bean(name = "projectDataSource")
public DataSource dataSource() {
return new ProjectDataSource();
}
There is no injection but a simple new object and ...
public class ProjectDataSource extends AbstractDataSource {
#Autowired ToolService toolService;
#ConfigurationProperties(prefix = "project.datasource")
private DataSource determineTargetDataSource() {
String projectName = toolService.get().getProjectName();
...
}
toolService will be null, so determineTargetDataSouce will fail with a null pointer exception.

SpringBoot Not able to load DataSource

I am trying to use datasource with spring boot.
In dev the application will run as spring bootrun. But in Test / Prod it will be external tomcat.
So in dev property file I am using Datasource details:
spring.community_ds.url=xxx
spring.community_ds.username=xxx
spring.community_ds.password=xxx
spring.community_ds.driver-class-name=oracle.jdbc.OracleDriver
spring.community_ds.driverClassName=oracle.jdbc.OracleDriver
And in TEST/PROD want to use JNDI
spring.community_ds.jndi-name=xxxx
Now in code I am trying to get the DataSource to create JdbcTemplate
#ConfigurationProperties(prefix = "spring.community_ds")
#Bean(name = "communityDb")
public DataSource communityDbDataSource() {
DataSource ds = DataSourceBuilder.create().build();
//Getting error db url is Null here
return ds;
}
#Bean(name = "communityDbTemplate")
public JdbcTemplate communityDbTemplate(#Qualifier("communityDb") DataSource communityDb) {
return new JdbcTemplate(communityDb);
}
I also tried :
#Configuration
public class DatabaseConfig {
#Autowired
Environment env;
#ConfigurationProperties(prefix = "spring.datasource")
#Bean
#Primary
public DataSource getDataSource() {
DataSource dsp = DataSourceBuilder
.create().build();
System.out.println(env.getProperty("spring.community_ds.url"));
System.out.println(env.getProperty("spring.datasource.url"));
return dsp;
}
}
Here also I saw env.getProperty is printing the data properly, but when I debugged inside DataSourceBuilder the url/username etc are null.
In gradle first I used:
compile("org.springframework:spring-jdbc")
Which was giving some error hence used:
compile("org.springframework.boot:spring-boot-starter-jdbc")

Unable to lookup JDBC datasource by JNDI

I am using Spring Data, Hibernate and jBoss 6.x.x.
I would like to look up at the jBoss 6.x.x the already configured jdbc datasource by JNDI.
Looking at the file standalone.xml, I have found the following entries:
<profile>
...
<datasources>
...
<datasource enabled="true" jndi-name="name_of_the_ds" pool-name="name_of_the_pool" use-java-context="true">
<connection-url>connection_uri</connection-url>
<driver>driver_name</driver>
<security>
<user-name>fake_login</user-name>
<password>fake_password</password>
</security>
</datasource>
...
</datasources>
...
</profile>
Based on this, I have written the following Spring annotation configuration
class for the data base (I am using Spring Data and Hibernate as the JPA provider)
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(basePackages = "dao.repository")
#PropertySource("classpath:application.properties")
public class DataBaseContextConfiguration {
private static final Logger LOGGER = LoggerFactory.getLogger(DataBaseContextConfiguration.class);
private Database dataBase = Database.SOME_DATA_BASE;
#Value("${jpa.showSql}")
private Boolean showSql;
#Value("${name.data.source}")
private String dataSourceJndiName;
#Bean
public LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean() throws NamingException {
final LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
localContainerEntityManagerFactoryBean.setDataSource(dataSource());
localContainerEntityManagerFactoryBean.setPackagesToScan(PACKAGE_WITH_DB_ENTITIES);
JpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
localContainerEntityManagerFactoryBean.setJpaVendorAdapter(jpaVendorAdapter);
return localContainerEntityManagerFactoryBean;
}
#Bean
public PlatformTransactionManager platformTransactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
jpaTransactionManager.setEntityManagerFactory(entityManagerFactory);
return jpaTransactionManager;
}
public DataSource dataSource() throws NamingException {
DataSource dataSource = null;
JndiTemplate jndi = new JndiTemplate();
dataSource = (DataSource) jndi.lookup(dataSourceJndiName);
return dataSource;
}
}
The String dataSourceJndiName has the following value name_of_the_ds.
When I am trying to run simple integration test the following exception occurres:
Caused by: javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial

Categories

Resources