I am trying to inject annotated by #Repository class in #ServerEndpoint class. But when i am trying to call repository method it is return null. Another injected bean from this package is working fine.
#ApplicationScoped
#ServerEndpoint("/WebsocketHome/actions")
public class WebSocketServer {
private static final Logger LOG = Logger.getLogger(WebSocketServer.class);
#Inject
private SessionHandler sessionHandler;
#Inject
private PlaceRepository placeRepository;
#OnMessage
public void handleMessage(String message, Session session) {
JSONParser jsonParser = new JSONParser();
try {
JSONObject jsonObject = (JSONObject) jsonParser.parse(message);
if ("getRooms".equals(jsonObject.get("action"))) {
List<Place> places = this.placeRepository.getAllPlaces(); //error is here
}
} catch (ParseException e) {
LOG.error(e.getMessage());
}
.....
This is repository class:
#Repository
#Transactional
public class PlaceRepository {
#Autowired
private SessionFactory sessionFactory;
#SuppressWarnings("unchecked")
public List<Place> getAllPlaces() {
return this.sessionFactory.getCurrentSession().createQuery("from Place place").list();
}
}
web.xml:
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/application-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
app-context.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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath:application.properties" system-properties-mode="ENVIRONMENT"/>
<context:component-scan base-package="com.hms.repository"/>
<context:component-scan base-package="com.hms.utils"/>
<tx:annotation-driven transaction-manager="txManager"/>
<import resource="security-context.xml"/>
<bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${db.driverClassName}" />
<property name="url" value="${db.url}" />
<property name="username" value="${db.username}" />
<property name="password" value="${db.password}" />
<!--
<property name="initialSize" value="5" />
<property name="maxActive" value="10" />
<property name="maxIdle" value="5" />
<property name="minIdle" value="2" />
-->
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:hibernate.cfg.xml"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${db.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hbm2ddl.auto">${db.hbm2ddl.auto}</prop>
</props>
</property>
</bean>
</beans>
Error appears only on calling of #OnMessage method.
All junit #Tests of repository class returns fine results.
What is wrong in my code?
Sorry for my english.
UPD:
It seems, that problem is in SessionFactory dependency because test method, that i add in #Repository:
public String testWS() {
return "Test is ok!";
}
returns fine result.
So, looks like i found the right way. I found it in Spring websocket documentation.
There are some steps what i did:
I put in type-level annotation:
#ServerEndpoint(value = "/WebsocketHome/actions", configurator = SpringConfigurator.class)
I added #Service and #Controller to my websocket classes and "context:component-scan" path to my app-context.xml file so that Spring can find corresponding beans.
I added the "spring-websocket" dependency in my pom.xml (i use maven)
Maybe it is not the right way, but it is works fine for me.
#Today jan 31' 2022 Just Add "spring-websocket" dependency
Related
I already searching about my error but I got nothing. still error in my code so i have to post my question here.
I got an error when I run my project in eclipse with tomcat server.
I already finish the project in Spring MVC 4 + Hibernate with MongoDB. now I have to switch into Hibernate with MySQL, I am starting the project in eclipse. but when I complete the configuration of spring with hibernate its shows error.
error and structure of project are following below:
enter image description here
web.xml
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>ApplicationContext</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<servlet>
<servlet-name>DMS_MySQL</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DMS_MySQL</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/assets/*</url-pattern>
</servlet-mapping>
<error-page>
<error-code>404</error-code>
<location>/pages/error/error404.jsp</location>
</error-page>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
</web-app>
SpringMVC-servlet.xml
<?xml version="1.0" encoding="UTF-8"?
<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=" //urls//">
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
<bean id="tilesviewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.tiles3.TilesView" />
<property name="order" value="2"></property>
</bean>
<bean id="jstlviewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/pages/" />
<property name="suffix" value=".jsp" />
<property name="order" value="3"></property>
</bean>
</beans>
applicationContext.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:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- Enable autowire -->
<context:annotation-config />
<context:component-scan base-package="com.cs" />
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />
<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/dms" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<!-- Session Factory Declaration -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.cs.bean" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.enable_lazy_load_no_trans">true</prop>
<prop key="hibernate.default_schema">test</prop>
<prop key="format_sql">true</prop>
<prop key="use_sql_comments">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<import resource="/WEB-INF/SpringMVC-servlet.xml"/>
</beans>
LoginController.java
package com.cs.controller;
public class LoginController {
#Autowired
private UserService userService;
#RequestMapping(value="/login")
public String execute(HttpSession session, Model model) throws Exception {
model.addAttribute("user", new UserBean());
UserBean tempUser = (UserBean) session.getAttribute("USER");
if (tempUser != null) {
return "redirect:/home";
}
return "logn";
}
#RequestMapping(value="/performLogin", method = RequestMethod.POST)
public String loginProcess(HttpSession session, Model model, #ModelAttribute("user") UserBean user,
BindingResult result) throws Exception
{
UserBean tempUser = (UserBean) session.getAttribute("USER");
if(tempUser != null)
{
return "redirect:/home";
}
if(user == null)
{
model.addAttribute("user", new UserBean());
return "login";
}
if(StringUtils.isBlank(user.getName()))
{
result.rejectValue("name", "error.required.username");
}
if(StringUtils.isBlank(user.getPassword()))
{
result.rejectValue("password", "error.required.password");
}
if(!result.hasErrors())
{
tempUser = userService.findByCredential(user);
if(tempUser != null)
{
if (tempUser.getRole().equals(RoleEnum.ADMIN)) {
session.setAttribute("USER", tempUser);
return "redirect:/home";
} else if (tempUser.getRole().equals(RoleEnum.CASHIER)) {
session.setAttribute("USER", tempUser);
return "redirect:/cHome";
}
}
else
{
result.reject("error.valid.usernamePassword");
}
}
user.setMobile("");
model.addAttribute("user", user);
return "login";
}
}
Thank you in advance.
Try http://localhost:8080/DMS_MySQL/login.
Also try changing your login controller as:
#RequestMapping(value = {"/login", "/"}, method = RequestMethod.GET)
public String execute(HttpSession session, Model model) throws Exception {
model.addAttribute("user", new UserBean());
UserBean tempUser = (UserBean) session.getAttribute("USER");
if (tempUser != null) {
return "redirect:/home";
}
return "login";//typo in your code
}
I assume you have defined mapping for login in tiles configuration.
here i find this sentence
<param-value>/WEB-INF/applicationContext.xml</param-value>
and where is your applicationContext.xml
This question already has answers here:
Why does Spring MVC respond with a 404 and report "No mapping found for HTTP request with URI [...] in DispatcherServlet"?
(13 answers)
Closed 6 years ago.
I tried all the trails posted in internet mainly in stackoverflow but coudn't find the exact solution of my application problem.
Please don't mark this as duplicate because warning might be the duplicate but version or something else is causing which is not duplicate here i.e the same answers are no working for me
Warning i'm getting:
WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI in DispatcherServlet with name 'appServlet'
Code of my application:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
servlet-context.xml
<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-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<!-- <annotation-driven /> -->
<!-- <context:annotation-config/> -->
<mvc:annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<!-- <resources mapping="/resources/**" location="/resources/" /> -->
<!-- Resolves views selected for rendering by #Controllers to .jsp resources
in the /WEB-INF/views directory -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<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://localhost:3306/TestDB" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<!-- Hibernate 4 SessionFactory Bean definition -->
<bean id="hibernate4AnnotatedSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.mahender.web.model.Person</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="personDAO" class="com.mahender.web.DAO.PersonDAOImpl">
<property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</bean>
<bean id="personService" class="com.mahender.web.service.PersonServiceImpl">
<property name="personDAO" ref="personDAO"></property>
</bean>
<context:component-scan base-package="com.mahender.web" />
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</bean>
Snippet of my Controller(not all the code provided i think this is enough to find the problem)
#RequestMapping(value = "/app")
#Controller
public class PersonController {
private PersonService personService;
#Autowired(required=true)
#Qualifier(value="personService")
public void setPersonService(PersonService ps){
this.personService = ps;
}
#RequestMapping(value = "/persons", method = RequestMethod.GET)
public String listPersons(Model model) {
model.addAttribute("person", new Person());
model.addAttribute("listPersons", this.personService.listPersons());
return "person";
}
and the jsp snippet of code is:
person.jsp
<c:url var="addAction" value="/person/add" ></c:url>
<form:form action="${addAction}" commandName="person">
You need to add this on your code.
model.setViewName("person");
model.addAttribute("person", new Person());
and also make sure your .jsp file is inside /views folder
Your requested action is not mapped properly in controller try to changed it to app/person/add
I am building a spring + hibernate application. I'm getting a 404 error, when I run the project. The compiler does not show any error messages, it indicates that the application server (tomcat 7) loads the servlet, but does not display the root page indicated in the controller class.
Help please......
Config.....
`
<?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"
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.0.xsd">
<context:property-placeholder location="classpath:resources/database.properties" />
<context:component-scan base-package="langS.com" />
<tx:annotation-driven transaction-manager="hibernateTransactionManager" />
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<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.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<value>com.langS.model.Employee</value>
<value>com.langS.EmployeeBean</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
</props>
</property>
</bean>
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>`
Controller
#Controller
public class NewController {
#Autowired
private EmployeeService employeeService;
#RequestMapping(value = "/index", method = RequestMethod.GET)
public String welcomeHome(){
return "index";
}
#RequestMapping(value = "/addEmployee", method = RequestMethod.GET)
public String addEmployeeRecord(){
return "addEmployee";
}
#RequestMapping(value = "/employeeList", method = RequestMethod.GET)
public String listEmployeesPage(){
return "employeesList";
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemalocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>sdnext</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>sdnext</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
404 means, that your tomcat server is getting the request, but does not now how to process the given request path.
In other words you have a bug in your URL or your configuration does not what you want it to do.
We need your configuration and desired URL to help you.
The problem is that you map the dispatcher servlet only to *.html, but you map you Controllers without using the .html suffix.
To make it work, either map you controller differently, ie :
#RequestMapping(value = "/index.html", method = RequestMethod.GET)
public String welcomeHome(){
return "index";
}
OR (and what I would do) :
Map you dispatcher servlet to all requests in web.xml :
<servlet-mapping>
<servlet-name>sdnext</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Then if you want to call your application with a url looking like this :
http://somehost:someport/YourApplication/
Then you'll need to map some controller method like this :
#RequestMapping(value = {"/", "/index"}, method = RequestMethod.GET)
public String home() {
// your code here
}
This way, calling http://somehost:someport/YourApplication/ OR http://somehost:someport/YourApplication/index will result in the same controller method being called.
I have a Spring Web application with two Hibernate data sources, and they are being managed with two separate transaction managers. The datasources are completely independent, schema-wise. This configuration passes all unit tests and integration tests, but when I deploy it in Jetty, the repository operations fail with the below exception:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named my_transactionManager1' is defined: No unique PlatformTransactionManager bean found for qualifier 'my_transactionManager1'
at org.springframework.beans.factory.annotation.BeanFactoryAnnotationUtils.qualifiedBeanOfType(BeanFactoryAnnotationUtils.java:84)
at org.springframework.beans.factory.annotation.BeanFactoryAnnotationUtils.qualifiedBeanOfType(BeanFactoryAnnotationUtils.java:55)
at org.springframework.transaction.interceptor.TransactionAspectSupport.determineTransactionManager(TransactionAspectSupport.java:246)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:100)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:625)
at my.controller.Class$$EnhancerByCGLIB$$3976e5ef.myMethodCall(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
persistence.xml
<persistence-unit name="pu1">
<properties>
<property name="hibernate.dialect" value="${hibernate.dialect}" />
<property name="hibernate.connection.url" value="${network.db.url}" />
<property name="hibernate.connection.driver_class" value="${hibernate.connection.driver_class}" />
<property name="hibernate.connection.username" value="{db.username}" />
<property name="hibernate.connection.password" value="{db.password}" />
<property name="hibernate.enable_lazy_load_no_trans" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="${hibernate.hbm2ddl.auto}" />
<property name="hibernate.show_sql" value="false" />
</properties>
Looking at the logs, both datasources seems to behave sanely (until this error occurs). Below is the 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"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<tx:annotation-driven transaction-manager="my_transactionManager1" />
<context:component-scan base-package="com.my.package"/>
<jpa:repositories
base-package="com.my.package" entity-manager-factory-ref="my_entityManagerFactory" transaction-manager-ref="my_transactionManager1">
</jpa:repositories>
<bean id="my_dataSource1" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="${my.db1.url}"/>
<property name="username" value="${db1.username}"/>
<property name="password" value="${db1.password}"/>
</bean>
<bean id="my_entityManagerFactory1"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="pu1" />
<property name="dataSource" ref="my_dataSource1" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value="${hibernate.dialect}"/>
<property name="generateDdl" value="false" />
<property name="database" value="HSQL"/>
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
</props>
</property>
</bean>
<bean id="my_transactionManager1" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="my_entityManagerFactory1" />
<property name="dataSource" ref="my_dataSource1" />
<qualifier value="my_transactionManager1"/>
<property name="persistenceUnitName" value="pu1"/>
</bean>
</beans>
My Service Class where I'm trying to inject the TransactionManager:
Service
#Transactional(value="my_transactionManager1")
#PersistenceContext(unitName = "pu1", name="my_entityManagerFactory1")
public class MyServiceClass{
#Autowired
private Field myField
#Resource(name="my_transactionManager1")
private JpaTransactionManager my_transactionManager1;
/**
* Public no-arg constructor for bean initialization
*/
public MyServiceClass() {}
/**
* Protected IOC constructor for testing
*
* #param resultsService
*/
protected MyServiceClass(Field myField) {
this.myField = myField;
}
I have tried a lot of different approaches to work around this problem. One thing that is often suggested for this situation is a single JTA XA TransactionManager, but I would like to avoid that, at least for this first pass. Another thing that is suggested is using an AbstractDataRoutingSource, but I don't really want that either. The approach I have seems tenable (if not optimal), because tests are passing and the application deploys without error. Here is my web.xml (sorry for lengthy post):
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="site" 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">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:my-first-context-file.xml,
classpath:a-few-other-config-files.xml,
</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
<servlet>
<servlet-name>MyServeletName</servlet-name>
<servlet-class>
com.sun.jersey.spi.spring.container.servlet.SpringServlet
</servlet-class>
<init-param>
<param-name>
com.sun.jersey.config.property.packages
</param-name>
<param-value>com.my.package</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
</load-on-startup>
</servlet>
<!--More servlets -->
<!-- Servlet mapping stuff -->
</web-app>
Any help at all would be much appreciated.
Make sure, you have unique ids of beans. It seems like you have 2 transactionManager beans with id="my_entityManagerFactory1"
Any way, you should add to annotation propagation value:
#Transactional(propagation=Propagation.REQUIRED, value="my_entityManagerFactory1")
Similar problem (one entity in 2 databases) I have solved by inheritence:
#MappedSuperclass
public class User{
private String name;
private String surname;
private String login;
private String password;
}
#Entity
public class Employee extends User{
//....
}
#Entity
public class CLient extends User{
//...
}
Employee and Client classes were in different subpackages of entity package.
One sessionFaction scanned first subpackage, other sessionFactory scanned second one.
I had two services with #Transaction annotation like above and serched both databases by one manager class.
On application I used only User entity
I "solved" the problem by combining the two databases into one.
Sorry if I mess up with my question, I am just getting started configuring MVC, Spring, etc....
The issue that I am running into is that in my Spring MVC project all of my Autowired services are being successfully autowired when my application deploys (verified by setting breakpoints in Spring Tool Suite), but when I try to invoke a autowired service's method I run into a NullPointerException. I have looked all over at different configuration files and it seems like my servelt-context, root-context and web XML files should be ok (don't quote me on that and they are included below).
I am wondering if somehow I am not invoking the instance of the service created at deploy time? It seems strange that the Autowired setters can be called successfully but then the services end up being null. Any help you can provide is greatly appreciated!
root-context.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:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="packagesToScan" value="com.byteslounge.spring.tx.model" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDrive" />
<property name="url"
value="jdbc:oracle:thin:#**********" />
<property name="username" value="*******" />
<property name="password" value="*******" />
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="dataSource" ref="dataSource" />
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven />
<context:annotation-config />
<bean
class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<context:component-scan base-package="com.clm.billing" />
servelt-context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
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">
<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<mvc:annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<mvc:resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources
in the /WEB-INF/views directory -->
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
</beans:beans>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>OrderList</display-name>
<servlet-name>OrderList</servlet-name>
<servlet-class>com.clm.billing.Oracle.OrderList</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>OrderList</servlet-name>
<url-pattern>/OrderList</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>EditBilling</display-name>
<servlet-name>EditBilling</servlet-name>
<servlet-class>com.clm.billing.EditBilling</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>EditBilling</servlet-name>
<url-pattern>/EditBilling</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>UpdateBilling</display-name>
<servlet-name>UpdateBilling</servlet-name>
<servlet-class>com.clm.billing.UpdateBilling</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UpdateBilling</servlet-name>
<url-pattern>/UpdateBilling</url-pattern>
</servlet-mapping>
</web-app>
InsuranceNoteDBServiceImpl:
(Here the setiNoteDAO is called with a instance of the iNoteDAO class, but when getNoteById is called iNoteDAO is null)
#Service
public class InsuranceNoteDBServiceImpl implements InsuranceNoteDBService {
private InsuranceNoteDAO iNoteDAO;
#Autowired
public void setiNoteDAO(InsuranceNoteDAO iNoteDAO) {
this.iNoteDAO = iNoteDAO;
}
#Override
#Transactional
public void insertNote(BillerNote note) {
iNoteDAO.insertNote(note);
}
#Override
#Transactional
public BillerNote getNoteById(int noteId) {
return iNoteDAO.getNoteById(noteId);
}
}
InsuranceNoteDBService:
public interface InsuranceNoteDBService {
void insertNote(BillerNote note);
BillerNote getNoteById(int noteId);
}
InsuranceNoteDAOImpl:
(Same thing happens here with the init() method that is setting the session factory)
#Service
public class InsuranceNoteDAOImpl implements InsuranceNoteDAO {
public SessionFactory sessionFactory;
#Autowired
public void init(SessionFactory factory) {
setSessionFactory(factory);
}
public void setSessionFactory(SessionFactory factory) {
this.sessionFactory = factory;
}
#Override
public void insertNote(BillerNote note) {
sessionFactory.getCurrentSession().save(note);
}
#Override
public BillerNote getNoteById(int noteId) {
return (BillerNote) sessionFactory.
getCurrentSession().
get(BillerNote.class, noteId);
}
}
InsuranceNoteDAO:
public interface InsuranceNoteDAO {
void insertNote(BillerNote note);
BillerNote getNoteById(int noteId);
}
Remove the init method and annotate the setter :
#Autowired
public void setSessionFactory(SessionFactory factory) {
this.sessionFactory = factory;
}