I have been working with the Spring framework for a few days trying to set up a project, based off of something like this tutorial.
Unfortunately, when i deploy the project using Tomcat, I get a screen that looks something like this:
I'm not really sure to go from here. I've checked the web.xml and any other relevant .xml files that would maybe affect the error, but I can't see an error. Below I will post my web.xml and spring-config.xml files.
web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>Campaign Spring V2</display-name>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
spring_config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:component-scan base-package="com.bridge.campaignspring.controller" />
<context:property-placeholder location="classpath:application.properties" />
<!-- Enables the Spring MVC #Controller programming model -->
<mvc:annotation-driven />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.bridge.campaignspring.Campaign</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="CampaignDao" class="com.bridge.campaignspring.dao.CampaignDAOImpl" />
<bean id="CampaignService" class="com.bridge.campaignspring.service.CampaignServiceImpl" />
</beans>
If need be, I can post the project to GitHub to see if there is an even larger flaw that could be found in the code. Also, if any other parts of the project need to be posted I will update the OP to display anything. Thanks!
EDIT: http://localhost/ does not load either, I was incorrect with my previous statement.
EDIT2: Here is a link to the project on GitHub.
EDIT3: After going through the Spring tutorial again this was resolved!
You didn't follow the tutorial well. The controller mapping starts with
#RequestMapping("/")
public class AppController {
The first annotation #RequestMapping("/") is important for spring to calculate the path used by the request.
And this code is missing
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] { "com.bridge.compaignspring.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
Without it Spring cannot autowire properties that depend on sessionFactory.
Just done a quick check through the github project, you have more problems that I thought.
You are using XML config to create the DispatchServer with the config at Spring-config.xml, while also having a AppInitializer on the class path.
The AppInitializer uses AppConfig which creates a Datasource bean, your XML also creates a Datasource bean and also a SessionFactory.
Tomcat will find the AppInitializer and is running through that first.
This means it tries to autowire the SessionFactory before the one in the XML have been created.
To move your code off this problem do the following things.
move spring_config.xml from /webapp/WEB-INF to /resources
add the following #import line to AppConfig.java
#Configuration
#EnableWebMvc
#ImportResource("classpath:spring-config.xml")
#ComponentScan(basePackages = "com.bridge.campaignspring")
public class AppConfig {
Now you need to remove 1 of the 2 DataSource beans you are creating. I would suggest removing the one in the XML as that is using invalid property values. i.e. ${database.driver} does not exist.
After you have made those changes, you will still have other problems, but you are further along than you were.
did u set Web Module Path in tomcat settings ?
refer these question Unable to run Spring REST application using Tomcat
Related
I am trying to build rest api with spring mvc and maven web project; however, when I try to run it on server it returns 404 on any url.
"The origin server did not find a current representation for the target resource or is not willing to disclose that one exists."
I've tried to find the solution on the internet and none of them worked for me. I think there might be some mistakes in my configuration but I don't know what. The project is build on eclipse using maven web project, using spring-mvc and hibernate with database mysql. I am kind of confused because there is no error in the log.
Below is my web.xml that I put inside src/main/webapp/WEB-INF
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<servlet-name>Dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/com/test/restlearning/applicationContext/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Below is my applicationContext.xml that I put inside src/main/resources/com/test/restlearning/applicationContext
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-5.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-5.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-5.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.test.restlearning.controller" />
<mvc:annotation-driven />
<mvc:default-servlet-handler />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/restlearning" />
<property name="username" value="root" />
<property name="password" value="" />
<property name="initialSize" value="5" />
<property name="maxActive" value="10" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.test.restlearning.dto"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="personDao" class="com.test.restlearning.dao.impl.PersonDAOImpl">
<constructor-arg ref="sessionFactory" />
</bean>
<bean id="personService" class="com.test.restlearning.service.impl.PersonServiceImpl">
<consrtuctor-arg ref="personDao" />
</bean>
and below is one of my controller
#CrossOrigin
#RestController
#RequestMapping("/persons")
public class PersonController {
#Autowired
#Qualifier("personService")
private PersonService personService;
#RequestMapping(method= RequestMethod.GET, headers = "Accept=application/json")
public Object getAll(HttpServletRequest request, HttpServletResponse response) {
try {
List<Person> persons = personService.getAll();
String url = ServletUtil.unwrap(request);
String json = PersonJSONWrapper.wrap(persons,url);
return ResponseEntity.ok(json);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
}
}
public static String getURL() {
return "/persons";
}
public static String getURL(Integer id) {
return "/persons"+id.toString();
}
}
I would be glad if you could point out my mistakes.
It looks like there is no bean PersonService in application context. Add PersonService class to applicationContext.xml as bean.
I have developed a JAX-WS based web-service. I have Web service layer, service layer and a Dao layer. When i call a service method from web service class it gives null pointer exception. The reason is the service class bean is not getting injected.
web-service class:
package com.test.webservice.controller;
import javax.jws.WebMethod;
import javax.jws.WebService;
import com.test.salary.service.SalaryService;
#WebService
public class EmployeeSalaryWebService {
private SalaryService salaryService;
/**
* #param salaryService the salaryService to set
*/
#WebMethod(exclude = true)
public void setSalaryService(SalaryService salaryService) {
this.salaryService = salaryService;
}
#WebMethod
public double getEmployeeSalary(String name){
System.out.println("==== Inside getEmployee Salary === "+salaryService );
return salaryService.calculateSalary(name);
}
}
Application-context
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean name="salaryWebService"
class="com.test.webservice.controller.EmployeeSalaryWebService">
<property name="salaryService" ref="salaryService" />
</bean>
<bean name="salaryService" class="com.test.salary.service.SalaryServiceImpl">
<property name="salaryDAO" ref="salaryDAO" />
</bean>
<bean name="salaryDAO" class="com.test.salary.dao.SalaryDaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#localhost:1521:xe" />
<property name="username" value="LOCAL" />
<property name="password" value="abcdef" />
</bean>
</beans>
web.xml:
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/salaryConfiguration.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
Please let me know why the SalaryService salaryService not getting injected.
Your service class and bean in context is two separate things. I believe that you don't get bean from context and just use class, aren't you?
I advice you marking your service class with
#Component
That will make your class to become spring bean.
Then you can use inside following annotation.
#Autowired
This will try to find appropriate bean with annotated element type in spring context.
And don't forget to put into your context.
<context:component-scan base-package="..." />
This will search all classes marked as #Component and add it to spring context as beans.
For more detailed instruction you can check this article
https://www.javacodegeeks.com/2010/11/jaxws-with-spring-and-maven-tutorial.html
Make your SalaryService auto wired as follows:
public class EmployeeSalaryWebService {
#Autowired
private SalaryService salaryService;
....
I am trying to get a simple Spring Integration test working to retrieve messages from a JMS queue hosted by HornetQ on JBoss EAP (version 6.4.0.GA running on Windows 7 Pro) running in standalone mode (standalone.bat -c standalone-full.xml).
The JMS test ran fine when using a simple Java JMS program; now, I'm trying to add Spring Integration and I get the following error:
18:29:03,197 ERROR [org.springframework.jms.listener.DefaultMessageListenerContainer]
(org.springframework.jms.listener.DefaultMessageListenerContainer#0-1)
Could not refresh JMS Connection for destination 'anotherQueue' -
retrying in 5000 ms. Cause: AOP configuration seems to be invalid:
tried calling method [public abstract javax.jms.Connection javax.jms.ConnectionFactory.createConnection()
throws javax.jms.JMSException] on target [HornetQQueue[anotherQueue]];
nested exception is java.lang.IllegalArgumentException: java.lang.ClassCastException#511504f4
The Spring config files are:
applicationContext-ordering-inbound-jms-spring-integration.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop=...
<bean id="jndiTemplateBilling" class="org.springframework.jndi.JndiTemplate">
<property name="environment">
<props>
<prop key="java.naming.factory.initial">org.jboss.as.naming.InitialContextFactory</prop>
<prop key="java.naming.provider.url">remote://localhost:4447</prop>
</props>
</property>
</bean>
<bean id="jndiObjectFactoryBeanBilling" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiTemplate" ref="jndiTemplateBilling" />
<property name="jndiName" value="java:jboss/exported/jms/queue/anotherQueue" />
<property name="lookupOnStartup" value="false" />
<property name="proxyInterfaces">
<list>
<value>javax.jms.QueueConnectionFactory</value>
<value>javax.jms.TopicConnectionFactory</value>
<value>java.io.Externalizable</value>
</list>
</property>
</bean>
<bean id="jndiDestinationResolver"
class="org.springframework.jms.support.destination.JndiDestinationResolver">
<property name="jndiTemplate" ref="jndiTemplateBilling" />
<property name="cache" value="true" />
</bean>
<int-jms:inbound-gateway
request-destination-name="anotherQueue"
request-channel="inboundOrderingBillingJms"
destination-resolver="jndiDestinationResolver"
connection-factory="jndiObjectFactoryBeanBilling" />
<int:channel id="inboundOrderingBillingJms" /> <!-- handled by OrderingBillingInboundEndpoint -->
<context:component-scan base-package="com.att.ordering.endpoints.jms" />
<context:annotation-config />
<context:spring-configured />
<int:annotation-config />
</beans>
and applicationContext-ordering-inbound-jms.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans ...">
<context:annotation-config />
<context:spring-configured />
<int:annotation-config />
<context:component-scan base-package="com.att.ordering.endpoints.jms"/>
</beans>
The ServiceActivator class:
package com.att.ordering.endpoints.jms;
import javax.xml.bind.JAXBElement;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
#Component
public class OrderingBillingInboundEndpoint
{
#ServiceActivator(inputChannel = "inboundOrderingBillingJms")
//public void handleMessage(JAXBElement<String> accountNumber)
public void handleMessage(String accountNumber)
{
System.out.println("In OrderingBillingInboundEndpoint.handleMessage - accountNumber=" + accountNumber);
}
}
I bootstrap spring with a WAR; WEB-INF/web.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>parentContextKey</param-name>
<param-value>ordering-spring-bootstrap.war.context</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</context-param>
</web-app>
WEB-INF/classes/beanRefContext.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="ordering-spring-bootstrap.war.context"
class="org.springframework.context.support.ClassPathXmlApplicationContext">
<constructor-arg>
<list>
<value>/applicationContext-ordering-inbound-jms-spring-integration.xml</value>
<value>/applicationContext-ordering-inbound-jms.xml</value>
</list>
</constructor-arg>
</bean>
</beans>
FOLLOWING ADDED AFTER ARTEM'S INITIAL REPLY
My JNDI name is java:jboss/exported/jms/queue/anotherQueue. It is bound to HornetQQueue[anotherQueue].
Following shows it in JBoss - note: there are 2 JNDI entries; I'm using the second one:
This is correct - I was able to get a Java JMS program (without Spring Integration) working as follows:
final Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
env.put(Context.PROVIDER_URL, "remote://localhost:4447");
env.put(Context.SECURITY_PRINCIPAL, "appuser");
env.put(Context.SECURITY_CREDENTIALS, "appuser1!");
context = new InitialContext(env);
// JNDI name in JBoss is: java:jboss/exported/jms/queue/anotherQueue
connectionFactory = (ConnectionFactory) context.lookup("jms/RemoteConnectionFactory");
destination = (Destination) context.lookup("jms/queue/anotherQueue");
connection = connectionFactory.createConnection("appuser", "appuser1!");
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
consumer = session.createConsumer(destination);
consumer.setMessageListener(new MyListener());
connection.start();
I am now trying to get the same simple example working using Spring Integration.
Questions:
(A) Where should I put the user id and password?
(B) Is the following correct? If not, what should it exactly be?
<bean id="jndiTemplateBilling" class="org.springframework.jndi.JndiTemplate">
<property name="environment">
<props>
<prop key="java.naming.factory.initial">org.jboss.as.naming.InitialContextFactory</prop>
<prop key="java.naming.provider.url">remote://localhost:4447</prop>
</props>
</property>
</bean>
(C) How should I change the following? I removed the proxyInterfaces; what else should change? I don't know how to use jee:jndi-lookup
<bean id="jndiObjectFactoryBeanBilling" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiTemplate" ref="jndiTemplateBilling" />
<property name="jndiName" value="java:jboss/exported/jms/queue/anotherQueue" />
<property name="lookupOnStartup" value="false" />
</bean>
(D) Does the following stay the same?
<bean id="jndiDestinationResolver"
class="org.springframework.jms.support.destination.JndiDestinationResolver">
<property name="jndiTemplate" ref="jndiTemplateBilling" />
<property name="cache" value="true" />
</bean>
(E) Does the following change?
<int-jms:inbound-gateway
request-destination-name="anotherQueue"
request-channel="inboundOrderingBillingJms"
destination-resolver="jndiDestinationResolver"
connection-factory="jndiObjectFactoryBeanBilling" />
Looks like you are wrong with your jndiObjectFactoryBeanBilling bean definition. It is for
<property name="jndiName" value="java:jboss/exported/jms/queue/anotherQueue" />
what is confirmed by the logs:
on target [HornetQQueue[anotherQueue]];
But it really must be for the javax.jms.ConnectionFactory:
connection-factory="jndiObjectFactoryBeanBilling"
So, just try to change the JNDI name to the correct one.
From other side I have never used all those proxyInterfaces options for JBOSS JNDI resources. They work well as is, e.g.:
<jee:jndi-lookup id="jndiMqConnectionFactory" jndi-name="${mqConnectionFactory}"/>
<jee:jndi-lookup id="auditQueue" jndi-name="queue/AuditQueue"/>
I am working on a project where we decided to add some interaction using jms and hornetq as provider.
I am quite new to Camel so I ran into a problem some if you may refer as trivial.
The goal was to initialize connection factory and add the jms component. However, as I understand it can't be done directly in the route configurator. So I created camel-config.xml and placed it to the resources/ directory.
I filled it in the following way:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:camel="http://camel.apache.org/schema/spring"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
<bean id="jndiTemplate" class="org.springframework.jndi.JndiTemplate">
<property name="environment">
<props>
<prop key="java.naming.factory.initial">org.jnp.interfaces.NamingContextFactory</prop>
<prop key="java.naming.provider.url">jnp://localhost:1099</prop>
<prop key="java.naming.factory.url.pkgs">org.jnp.interfaces:org.jboss.naming</prop>
</props>
</property>
</bean>
<bean id="jmsQueueConnectionFactory"
class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiTemplate">
<ref bean="jndiTemplate"/>
</property>
<property name="jndiName">
<value>ConnectionFactory</value>
</property>
</bean>
<bean name="jms" class="org.apache.camel.component.jms.JmsComponent">
<property name="connectionFactory" ref="jmsQueueConnectionFactory"/>
</bean>
</beans>
The project doesn't use Spring so it was the only example of the xml I have found that doesn't make use of Spring.
In the route configurator I use routeBuilder.from("jms:queue:top").to("...");
However, when I start the project it throws FailedToCreateEndpointException and states
"No component found with schema: jms".
I suppose that the xml file is simply not used but I just can't understand how to point to it.
Looking forward to hearing any advice.
The <beans/> XML is a Spring configuration that has to be bootstrapped in some way. You may have a look at the Tomcat ActiveMQ example found here, showing how to do that in a servlet environment. Have a special look at web.xml:
<!-- location of spring XML files -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:broker.xml,
classpath:camel-config.xml
</param-value>
</context-param>
<!-- the listener that kick-starts Spring, which loads the XML files and start our application -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Of course, you could also use a Java only setup as follows:
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false");
ModelCamelContext context = new DefaultCamelContext();
context.addComponent("jms", JmsComponent.jmsComponentAutoAcknowledge(connectionFactory));
I have a database project which is using spring. For that I have two important files in src/META-INF/spring/(database project)
The first one is the cmn-dao-spring.xml . The other one is the database.properties.
In my tomcat webapp project I am able to load with that code all the needed context-files:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:/META-INF/spring/*.xml
</param-value>
</context-param>
The problem is that the database.properties is not loaded.
If I change the xml to this:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:/META-INF/spring/*
</param-value>
</context-param>
I get the Exception:
Caused by: org.xml.sax.SAXParseException: Content is not allowed in prolog.
because the properties is no valid xml.
The startup of my tomcat fails.
How can I include the database.properties from my cmn-dao project in my webapp?
EDIT
That is my cmn-dao.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<tx:annotation-driven />
<context:annotation-config />
<!-- DATABASE CONFIGURATION -->
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>META-INF/spring/database.properties</value>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<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>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- BEAN DEFINITIONS -->
<bean id="scoreMapper" class="de.bc.qz.dao.mapper.ScoreMapper"
autowire="byName">
<constructor-arg value="s." />
</bean>
<bean id="scoreExtractor" class="de.bc.qz.dao.extractor.ScoreExtractor"
autowire="byName">
</bean>
<bean id="questionMapper" class="de.bc.qz.dao.mapper.QuestionMapper"
autowire="byName">
<constructor-arg value="q." />
</bean>
<bean id="complaintMapper" class="de.bc.qz.dao.mapper.ComplaintMapper"
autowire="byName">
<constructor-arg value="c." />
</bean>
<bean id="scoreDao" class="de.bc.qz.dao.ScoreDao" autowire="byName">
<property name="dataSource" ref="dataSource" />
<property name="LAUSFT">
<value>
SELECT * FROM (
SELECT s.*, #rank
:= #rank + 1 rank
FROM
quiz.score s, (SELECT #rank := 0) init
ORDER BY points DESC
) s
WHERE rank BETWEEN ? AND ?
ORDER BY rank;
</value>
</property>
<property name="LUS">
<value>
SELECT id
FROM quiz.score
WHERE username = ? AND uuid = ?;
</value>
</property>
</bean>
<bean id="complaintDao" class="de.bc.qz.dao.ComplaintDao"
autowire="byName">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="questionDao" class="de.bc.qz.dao.QuestionDao" autowire="byName">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
The JUnit's for cmn-dao works absolut correct and the placeholder works too.
Inside tomcat project I have added the related projects via Deployment Assembly.
Thx for your help
Stefan
use spring util to read properties file.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd">
<context:annotation-config />
<util:properties id="db_config" location="classpath:db_config.properties"></util:properties>
</beans>
user spring new '#value' annotation to get the property file key=value i.e
example : db_config.properties contains
db_user_name = uttesh
db_password = password
to get "db.user.name" property value use below code
#Value("#{db_config[db_user_name]}")
private String dbUsername;
contextCongifLocation is for spring configuration files only.
use this in your spring config (xml) file for loading properties:
<bean id="props" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath:META-INF/spring/database.properties"/>
</bean>
or
<context:property-placeholder location="classpath:META-INF/spring/database.properties" />
Try to use the util namespace instead, it allows to load several property files and separate them into property groups:
<util:properties id="application" location="classpath:application.properties"/>
To use the properties:
<bean id="postgresDataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="#{application.driverClassName}"/>
<property name="url" value="#{application.url}"/>
<property name="username" value="#{application.username}"/>
<property name="password" value="#{application.password}"/>
</bean>
This is the properties file example:
driverClassName=org.postgresql.Driver
url=jdbc:postgresql://localhost:5432/somedatabase
username=dummy
password=dummy
Change your context file to something like that :
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:/META-INF/spring/*.properties
</param-value>
</context-param>
Use contextConfigLocation in web.xml to read your main spring config xml file.
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:/META-INF/spring/spring-app-context.xml
</param-value>
</context-param>
import cmn-dao.xml in spring-app-context.xml
<import resource="classpath:/META-INF/spring/cmn-dao.xml" />
Now use PropertyPlaceholderConfigurer to read database.properties in cmn-dao.xml
<bean id="props" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath:META-INF/spring/database.properties"/>
</bean>
This is how you load property files into your spring context:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:property-placeholder location="classpath*:META-INF/spring/*.properties"/>
</beans>