I am new in spring, and I try to use it with hibernate to create tables from the entity class but it never works, here is my spring-cinfig.xml :
'
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:8889/testeleve"/>
<property name="username" value="root"/>
<property name="password" value="yassine"/>
</bean>
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="generateDdl" value="true"/>
<property name="database" value="MYSQL"/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
<!-- spring based scanning for entity classes-->
<property name="packagesToScan" value="Class"/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"/>'
and here is my test class :
'
#Autowired
private static CrudRepository repository;
public static void main(String[] args) {
AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
createEleve(22, "Saint", "Peter");
createEleve(23, "Jack", " Dorsey");
createEleve(24, "Sam", "Fox");
}'
and here is the exception:
Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [TestEleve2/resources/spring-config.xml]; nested exception is java.io.FileNotFoundException: class path resource [TestEleve2/resources/spring-config.xml] cannot be opened because it does not exist
just do one thing put your file spring-config.xml in to the TestEleve2/resources/ path and try to run program again it has to be run.
You should specify where is your spring-config.xml located. Try something like this:
#Autowired
private static CrudRepository repository;
public static void main(String[] args) {
AbstractApplicationContext context = new ClassPathXmlApplicationContext("/WEB-INF/resources/spring-config.xml");
createEleve(22, "Saint", "Peter");
createEleve(23, "Jack", " Dorsey");
createEleve(24, "Sam", "Fox");
}
Update
mvc-dispatcher-servlet.xml
<import resource="spring-config.xml"/>
Add below code in your web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>YourApp</display-name>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>YourApp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>YourApp</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Here, web.xml tries to see YourApp-servlet.xml file which is actually your web.xml.
you need to replace your spring-config.xml to YourApp-servlet.xml .
Here YourApp is your application name. Put it in webapps folder.
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.
like in topic, but if I will do just persistence.xml file in META-INF with unitName, and do that by this, then everything is good, and my sql query is working, and connection is open.
Here is my view of my project:
project structure
Here is code where I invoke method, my HomeController.java:
#Controller
#RequestMapping("/")
#SessionAttributes("/")
public class HomeController {
#Autowired
private UserDao userDao;
#Autowired
private EmployeeDAO employeeDao;
#RequestMapping(value = {"/dam"}, method = RequestMethod.GET)
public String setupForm(Model model)
{
userDao.getUserByUserId("2");
//employeeDao.getAllEmployees();
return "listEmployeeView";
}
}
Here is UserDao.java:
#Repository
#Transactional
public class UserDao {
#PersistenceContext
private EntityManager entityManager;
public UserModel getUserByUserId(String userId) {
UserModel user = null;
//EntityManagerFactory emf = Persistence.createEntityManagerFactory("movie-unit");
//entityManager = emf.createEntityManager();
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<UserModel> cq = cb.createQuery(UserModel.class);
Root<User> userRoot = cq.from(User.class);
cq.multiselect(
userRoot.get("firstName"),
userRoot.get("middleName"),
userRoot.get("lastName"),
userRoot.get("email"),
userRoot.get("userId"),
userRoot.get("password")
);
cq.where(cb.equal(userRoot.get("userId"), userId));
TypedQuery<UserModel> q = entityManager.createQuery(cq);
user = q.getSingleResult();
System.out.print(user.getUserId()+"&"+user.getPassword());
return user;
}
}
here is web.xml:
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring Hibernate JPA Hello World Application</display-name>
<!-- Configuration file for the root application context -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-servlet.xml
</param-value>
</context-param>
<!-- Configuration for the DispatcherServlet -->
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
and here is spring-servlet.xml:
<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:mvc="http://www.springframework.org/schema/mvc"
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-3.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<!-- It register the beans in context and scan the annotations inside beans and activate them -->
<context:component-scan base-package="com.howtodoinjava.demo" />
<!-- This allow for dispatching requests to Controllers by registering
two beans - DefaultAnnotationHandlerMapping and AnnotationMethodHandlerAdapter -->
<mvc:annotation-driven />
<!-- This helps in mapping the logical view names to directly view files under a certain pre-configured directory -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- This resolves messages from resource bundles for different locales -->
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages" />
</bean>
<!-- To validate the posted add employee form -->
<bean id="employeeValidator" class="com.howtodoinjava.demo.validator.EmployeeValidator" />
<!-- This produces a container-managed EntityManagerFactory;
rather than application-managed EntityManagerFactory as in case of LocalEntityManagerFactoryBean-->
<bean id="entityManagerFactoryBean" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- This makes /META-INF/persistence.xml is no longer necessary -->
<property name="packagesToScan" value="com.howtodoinjava.demo.model" />
<!-- JpaVendorAdapter implementation for Hibernate EntityManager.
Exposes Hibernate's persistence provider and EntityManager extension interface -->
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">validate</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
</props>
</property>
</bean>
<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/baza" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<!-- This transaction manager is appropriate for applications that use a single JPA EntityManagerFactory for transactional data access.
JTA (usually through JtaTransactionManager) is necessary for accessing multiple transactional resources within the same transaction. -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactoryBean" />
</bean>
<!-- responsible for registering the necessary Spring components that power annotation-driven transaction management;
such as when #Transactional methods are invoked -->
<tx:annotation-driven />
</beans>
Like I said, if I do entitymanager and entitymanagerfactory in java code which is commented here in UserDao.java with persistence.xml like this:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="movie-unit">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost/baza" />
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.username" value="root" />
<property name="hibernate.archive.autodetection" value="class" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
then everythings works fine.
In mysql server I have privileges like this:
Any % -- USAGE
Any localhost no password USAGE
root 127.0.0.1 no password ALL PRIVILEGES
root ::1 no password ALL PRIVILEGES
root localhost with password ALL PRIVILEGES
Where is problem?
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 use spring 3.2.8, hibernate 4. I have an error "org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.HibernateException: createCriteria is not valid without active transaction"
web.xml:
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>journeys</display-name>
<servlet>
<servlet-name>journeys</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>journeys</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/journeys-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<page-encoding>UTF-8</page-encoding>
</jsp-property-group>
</jsp-config>
</web-app>
journeys-servlet.xml:
<beans xmlns="...">
<context:annotation-config />
<context:component-scan base-package="journeys.*" />
<bean id="viewResolver"
...
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://myserver:3306/name" />
<property name="username" value="user" />
<property name="password" value="password" />
</bean>
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:annotation-driven />
</beans>
class/hibernate.cfg.xml:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Mapping files -->
<mapping class="journeys.entity.Company"/>
....
</session-factory>
</hibernate-configuration>
CompanyDAO:
package journeys.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import journeys.utils.Pair;
import journeys.entity.Company;
import journeys.entity.Journey;
import journeys.entity.JourneyDeparture;
import journeys.entity.Order;
#Component
public class CompanyDAO extends AbstractDAO<Company> {
#Autowired
private SessionFactory sessionFactory;
public CompanyDAO() {
super(Company.class);
}
#Transactional
#SuppressWarnings("unchecked")
public List<Company> f() {
return (List<Company>)sessionFactory.getCurrentSession().createCriteria(Company.class).list();
}
}
CompanyController:
package journeys.controller;
import journeys.dao.CompanyDAO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
#RequestMapping(value = "/company")
public class CompanyController {
#Autowired
CompanyDAO companydao;
#RequestMapping(value = {"", "/", "list"}, method = RequestMethod.GET)
public ModelAndView list() {
ModelAndView model = new ModelAndView("Company/list");
model.addObject("companies", companydao.f());
return model;
}
}
Do the following and the problem goes away:
In your hibernate.cfg.xml add the following property:
<property name="hibernate.current_session_context_class"> org.springframework.orm.hibernate4.SpringSessionContext
</property>
Also remove the line <property name="current_session_context_class">thread</property> that you currently have in your code
A common reason for this that I have seen is the lack of "engine" to apply the effect of #Transactional. Namely, in your pom you need to have a runtime dependency either on cglib or jaspect. Seeing how your tx-manager is defined, it seems you are likely to need cglib.
Edit:
Also, to enable cglib, use:
<tx:annotation-driven proxy-target-class="true" transaction-manager="txManager"/>
instead of just
<tx:annotation-driven transaction-manager="txManager" />