Property file could not be resolved - java

I have 2 maven modules - Webapp and Persistence. Persistence module has a property file - database.properties and two context files - persistenceContext.xml (main), datasourceContext.xml (imported to persistenceContext.xml).
persistenceContext.xml
<context:annotation-config/>
<tx:annotation-driven transaction-manager="transactionManager" />
<context:component-scan base-package="com.example.persistence"/>
<context:property-placeholder location="classpath:database.properties, classpath:application.properties" />
<import resource="classpath:datasourceContext.xml" />
Files persistenceContext.xml, datasourceContext.xml and database.properties are in directory resources of Persistence module.
datasourceContext.xml
<bean id="dataSource" destroy-method="close"
class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="${database.url}"/>
<property name="user" value="${database.username}"/>
<property name="password" value="${database.password}"/>
<property name="debugUnreturnedConnectionStackTraces" value="true"/>
<property name="unreturnedConnectionTimeout" value="20"/>
<property name="minPoolSize" value="5"/>
<property name="initialPoolSize" value="10"/>
<property name="maxPoolSize" value="50"/>
<property name="maxStatements" value="50"/>
<property name="idleConnectionTestPeriod" value="120"/>
<property name="maxIdleTime" value="1200"/>
</bean>
database.properties
database.url=jdbc:mysql://255.255.255.255:3306/...
database.username=...
database.password=...
Persistence maven module is dependency of Webapp module. When I deploy Webapp to Tomcat it failed with exception:
org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'dataSource' defined in class path resource [spring-datasource.xml]: Could not resolve placeholder 'database.url' in string value "${database.url}"
I tried the following solutions:
moved database.properties under directory path resources\com\example\persistence.
use property-placeholder or PropertyPlaceholderConfigurer in datasourceContext.xml instead of using property-placeholder in persistenceContext.xml.
moved database.properties under Webapp module and then try point 1.
I always convinced that database.properties file is under classpath of Persistence module.
Nothing from mentioned doesn't work, I looked also on other threads on stackoverflow and spring forum - but with no success.

Related

How can i make a Spring bean which can be configured in setters as well constructor dependency?

This is a question that was asked in an interview .
The question was that a bean has certain properties which we configure in .xml file and then we inject it but let's say that one does not know that the properties or the properties will be different for different Beans . So how will we make that bean so that we are able to configure it in runtime ?
I think externalizing the bean values, something like:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>classpath:com/foo/jdbc.properties</value>
</property>
</bean>
<bean id="dataSource" destroy-method="close"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
then following the example having your jdbc.properties file:
jdbc.driverClassName=org.hsqldb.jdbcDriver
jdbc.url=jdbc:hsqldb:hsql://production:9002
jdbc.username=sa
jdbc.password=root
the properties can be configured at runtime

Entity manager has not been injected

I just started working with Spring ROO and I generated my entity classes using the database reverse engineer command. However whenever I try to call one of the CRUD method in the generated entity class, I keep getting this exception :
java.lang.IllegalStateException: Entity manager has not been injected (is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)
I suspect(by looking at the generated files) that the EntityManager was not injected into the class. Please could you tell me what configuration I am missing?
Here is what my applicationContext.xml looks like
<context:property-placeholder location="classpath*:META-INF/spring/*.properties"/>
<context:spring-configured/>
<context:component-scan base-package="com.lennartz">
<context:exclude-filter expression=".*_Roo_.*" type="regex"/>
<context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
</context:component-scan>
<bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" id="dataSource">
<property name="driverClassName" value="${database.driverClassName}"/>
<property name="url" value="${database.url}"/>
<property name="username" value="${database.username}"/>
<property name="password" value="${database.password}"/>
<property name="testOnBorrow" value="true"/>
<property name="testOnReturn" value="true"/>
<property name="testWhileIdle" value="true"/>
<property name="timeBetweenEvictionRunsMillis" value="1800000"/>
<property name="numTestsPerEvictionRun" value="3"/>
<property name="minEvictableIdleTimeMillis" value="1800000"/>
<property name="validationQuery" value="SELECT 1 FROM DUAL"/>
</bean>
<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<tx:annotation-driven mode="aspectj" transaction-manager="transactionManager"/>
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory">
<property name="persistenceUnitName" value="persistenceUnit"/>
<property name="dataSource" ref="dataSource"/>
</bean>
And the generated entity files
privileged aspect UserDetail_Roo_Jpa_ActiveRecord {
#PersistenceContext
transient EntityManager UserDetail.entityManager;
public static final EntityManager UserDetail.entityManager() {
EntityManager em = new UserDetail().entityManager;
if (em == null) throw new IllegalStateException("Entity manager has not been injected (is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)");
return em;
}
Please let me know if there is something I'm missing.
You must not modify the .aj files, to customize the Roo generated code read http://docs.spring.io/spring-roo/docs/2.0.0.M1/reference/html/#edit-modify-and-customize-the-roo-generated-code
I eventually figured out the problem, it seems context was not being initialized in my application.
I added the following line in my web.xml and it worked
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:META-INF/spring/applicationContext*.xml</param-value>
</context-param>
If your application is not a web app, I assume initializing the context using ClassPathXmlApplicationContext should work for you.

how can i get database password at runtime before connecting to the database

in my applicationcontext.xml i have this :
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/dashboardsupervisor" />
<property name="username" value="root" />
<property name="password" value="1234" />
</bean>
here i am connecting with my database :
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"applicationContext.xml");
MySQLRdbHelper rdbHelper = (MySQLRdbHelper)
ctx.getBean("ManagerSupervisor");
What is want is to NOT read the password "1234" from my applicationcontext.xml
and read it from some properties file in my local drive .
as this will be running on different machines and every one have different passwords.
Can i achieve this .
thanks
Yes, you can, and the key to this is Springs PropertyPlaceholderConfigurer.
For example, you create a file on your file system called database.properties, containing your password (note, that you can also add more settings to this file, like username, JDBC url, etc).
jdbc.password=1234
Next, you need to declare a PropertyPlaceholderConfigurer bean and point it to the database.properties file:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>path/to/database.properties</value>
</property>
</bean>
Note that the path is interpreted as a classpath resource, unless it is prefixed with file:.
Finally, replace the configuration of your dataSource bean: replace
<property name="password" value="1234" />
with
<property name="password" value="${jdbc.password}" />
You could use profiles:
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.getEnvironment().setActiveProfiles("dev1");
ctx.load("*Context.xml");
ctx.refresh();
<bean id="database1" profile="dev1"/>
<bean id="database2" profile="dev2">
The best way is to create the data source in application server and configure as below in application.xml
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName"><value>YourDSName</value></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
.....
</bean>

Spring loading PropertySourcesPlaceholderConfigurer from JBoss context

I have a spring 3.1 application loading settings using PropertySourcesPlaceholderConfigurer and I want to manage test and production environments simply loading settings from server context overriding settings specified in local file properties.
Next example works fine with Tomcat, how can I do the same in JBoss AS 7.1?
In spring context I have:
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true" />
<property name="localOverride" value="false" />
<property name="locations">
<list>
<value>classpath:Application.properties</value>
<value>classpath:ApplicationTest.properties</value>
</list>
</property>
</bean>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${jdbc.driverClassName}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
In ApplicationTest.properties (that overrides Application.properties):
jdbc.driverClassName=oracle.jdbc.OracleDriver
jdbc.url=jdbc:oracle:thin:#XXXX:1521:xxxx
jdbc.username=myUsername
jdbc.password=myPassword
In context.xml (in Tomcat/conf directory):
<Context>
...
<Parameter name="jdbc.driverClassName" value="oracle.jdbc.OracleDriver" override="false"/>
<Parameter name="jdbc.url" value="jdbc:oracle:thin:#XXXX:1521:ProductionSID" override="false"/>
<Parameter name="jdbc.username" value="myProductionUsername" override="false"/>
<Parameter name="jdbc.password" value="myProductionPassword" override="false"/>
...
</Context>
In this way all parameters specified in context.xml overrides parameters in ApplicationTest.properties.
Is there a way to specify context parameter in JBoss? (i.e. in standalone.xml file)
EDIT - SOLVED:
As suggested in the answers, if I put entries in WEB-INF/jboss-web.xml inside webapp that works:
<jboss-web>
...
<env-entry>
<env-entry-name>jdbc.username</env-entry-name>
<env-entry-value>myUsername</env-entry-value>
<env-entry-type>java.lang.String</env-entry-type>
</env-entry>
...
</jboss-web>
But my goal was to put the config file out of webapp.
I solved in this way, I load the config file from $SERVER/conf directory:
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="false" />
<property name="localOverride" value="false" />
<property name="ignoreResourceNotFound" value="true" />
<property name="locations">
<list>
<value>classpath:Application.properties</value>
<value>classpath:ApplicationTEST.properties</value>
<value>file:${catalina.home}\conf\ApplicationPRODUCTION.properties</value><!-- FOR TOMCAT -->
<value>file:${jboss.server.base.dir}\configuration\ApplicationPRODUCTION.properties</value><!-- FOR JBOSS-->
</list>
</property>
</bean>
If someone knows how to put Parameters in JBOSS config out of webapp (as TOMCAT) is well appreciated!
Thanks All!
According to the JBoss7 documentation:
In AS7 the file context.xml is ignored. Most of the old context.xml
configuration has been moved to jboss-web.xml.
See here for more details.
In older versions you could add these properties to context.xml as usual - JBoss use Tomcat as a servlet container.
Use a jboss-web.xml file. This file specifically replaces context.xml from Tomcat.

FileNotFoundException while running Spring and Ibatis based application on Tomcat

I am using Spring, ibatis for ORM. My app-config.xml look like
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://192.168.10.50/lmexdb_v1" />
<property name="username" value="lmexdba" />
<property name="password" value="lmexdba123#" />
</bean>
<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
<property name="configLocation"
value="classpath:com/platysgroup/lmex/server/mobile/dao/ibatis/SqlMapConfig.xml" />
</bean>
<bean id="mobileController" class="com.platysgroup.lmex.server.controller.MobileController">
<property name="announcementService" ref="announcementService"></property>
<property name="courseService" ref="courseService"></property>
<property name="userService" ref="userService"></property>
</bean>
and I have my sqlmapconfig.xml file in src/webapp/spring.
But when I run my application on tomcat it show me a exception:
java.io.FileNotFoundException: class path resource [com/platysgroup/lmex/server/mobile/dao/ibatis/SqlMapConfig.xml] cannot be opened because it does not exist
put it in src , and it will be available
if you are using maven project then add it to resource

Categories

Resources