Injection of autowired dependencies failed while trying to access dao bean - java

I am getting an error while accessing the web page. here is my code -
web.xml file -
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
dispatcher servlet with name - "dispatcher-servlet.xml"
<context:annotation-config />
<context:component-scan base-package="com.webProject.controller"></context:component-scan>
<!-- <context:component-scan base-package="com.webProject">
<context:include-filter type="aspectj" expression="com.webProject.*" />
</context:component-scan>
-->
<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/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="mysqlDataSource" 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/school" />
<property name="username" value="root" />
<property name="password" value="test" />
</bean>
<bean id="mySessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="mysqlDataSource" />
<property name="annotatedClasses">
<list>
<value>com.webProject.model.Student</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect"> org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
<prop key="javax.persistence.validation.mode">none</prop>
<prop key="connection.autocommit">true</prop>
</props>
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="mySessionFactory" />
</bean>
<!-- <bean id="studentDao" class="com.webProject.dao.StudentDaoImpl"></bean>-->
</beans>
Student controller class -
package com.webProject.controller;
#Controller
#RequestMapping("/Student")
public class StudentController {
#Autowired
private IStudentDao studentDao;
//List<Student> students;
/*public StudentController() {
students = new ArrayList<Student>();
}*/
public IStudentDao getStudentDao() {
return studentDao;
}
public void setStudentDao(IStudentDao studentDao) {
this.studentDao = studentDao;
}
#RequestMapping(value="details/{number}",method=RequestMethod.GET)
public String studentDetails(#PathVariable("number") int studentNumber, Model model){
//Student student = this.students.get(studentNumber);
Student student = (Student) getStudentDao().load(new Long(studentNumber));
model.addAttribute("student",student);
model.addAttribute("studentNumber", Integer.toString(studentNumber));
return "studentDetails";
}
#RequestMapping(value="addStudent", method=RequestMethod.POST)
public String addStudent(#ModelAttribute("student") Student student, Model model){
if(student != null){
getStudentDao().save(student);
//this.students.add(student);
model.addAttribute("student", student);
model.addAttribute("studentNumber", Integer.toString(getStudentDao().count()));
return "studentAddSuccess";
}else{
throw new NullPointerException();
}
}
#RequestMapping(value="studentRegistration")
public String sendStudentForm(Model model){
Student student = new Student();
model.addAttribute("student", student);
return "studentForm";
}
#RequestMapping(value="delete/{studentNumber}")
public String deleteStudent(#PathVariable("studentNumber") int studentNumber, Model model){
Student student = (Student) getStudentDao().load(new Long(studentNumber));
model.addAttribute("std", student);
getStudentDao().deleteById(new Long(studentNumber));
return "deleteStudent";
}
}
studentform.jsp
<body>
<form:form method="post" modelAttribute="student" action="addStudent">
<table>
<tr>
<td>Student Name</td>
<td>form:input path="studentName"</td>
</tr>
<tr>
<td>Department</td>
<td>form:input path="department"</td>
</tr>
<tr>
<td>College</td>
<td>form:input path="collegeName"</td>
</tr>
<tr>
<td colspan="3"><input type="submit" /></td>
</tr>
</table>
</form:form>
</body>
when i mention -
this i get an error as "Resource not found". so i tried including all my packages as-
<context:component-scan base-package="com.webProject.controller"></context:component-scan>
<context:component-scan base-package="com.webProject.dao"></context:component-scan>
<context:component-scan base-package="com.webProject.model"></context:component-scan> but then also i get same "resource not found" error. i tried another way as mentioned in another thread - http://stackoverflow.com/questions/7914363/injection-of-autowired-dependencies-failed
<context:component-scan base-package="com.webProject">
<context:include-filter type="aspectj" expression="com.webProject.*" />
</context:component-scan>
but then also same result - "Resource not found".
so only when i give this base-package="com.webProject.controller", then i dont get "Resource not found error", but then it get another error -
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'studentController': Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.webProject.dao.IStudentDao
com.webProject.controller.StudentController.studentDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching
bean of type [com.webProject.dao.IStudentDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.
Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
then i tried to inject the studentDao as , then i also i get an error.
I am using Tomcat to deploy this artifact. and using maven to build this project. i am not sure how it spring+ hibernate+ maven project works in tomcat?
I have recently started programming using spring and hibernate and this is my first project using these technologies. so please pardon me if i am making some basic mistake.
can you please help me with some solution.
student Dao -
package com.webProject.dao;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import com.webProject.model.*;
public abstract class AbstractHibernateDAOImpl implements AbstractDao {
#Autowired
private HibernateTemplate hibernateTemplate;
public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
protected Class domainClass = getDomainClass();
/**
* Method to return the class of the domain object
*/
protected abstract Class getDomainClass();
#SuppressWarnings("unchecked")
public PersistentObject load(Long id) {
return (PersistentObject) getHibernateTemplate().load(domainClass, id);
}
public void update(PersistentObject t) {
getHibernateTemplate().update(t);
}
public void save(PersistentObject t) {
getHibernateTemplate().save(t);
}
public void delete(PersistentObject t) {
getHibernateTemplate().delete(t);
}
#SuppressWarnings("unchecked")
public List<PersistentObject> getList() {
return (getHibernateTemplate().find("from " + domainClass.getName()
+ " x"));
}
public void deleteById(Long id) {
Object obj = load(id);
getHibernateTemplate().delete(obj);
}
#SuppressWarnings("unchecked")
public void deleteAll() {
getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException {
String hqlDelete = "delete " + domainClass.getName();
int deletedEntities = session.createQuery(hqlDelete)
.executeUpdate();
return null;
}
});
}
public int count() {
List list = getHibernateTemplate().find(
"select count(*) from " + domainClass.getName() + " x");
Integer count = (Integer) list.get(0);
return count.intValue();
}
}
student dao interface -
package com.webProject.dao;
public interface IStudentDao extends AbstractDao{
}
student dao implementation -
package com.webProject.dao;
import org.springframework.stereotype.Repository;
import com.webProject.model.Student;
#Repository ("studentDao")
public class StudentDaoImpl extends AbstractHibernateDAOImpl implements IStudentDao{
#Override
protected Class getDomainClass() {
return Student.class;
}
}

If your DAO classes is placed in different packages with controller classes then you should change your component scan element:
<context:component-scan base-package="com.webProject">
Also check that you have annotated your DAO classes with #Repository (or #Component) annotation.

Related

Bean is not getting Autowired [duplicate]

This question already has answers here:
Why is my Spring #Autowired field null?
(21 answers)
Closed 6 years ago.
Hi Friends i am creating a simple application using Spring and JPA over Hibernate but i am getting a Null Pointer Exception while running the app as the beans are not getting initialised.Below is my application-context.xml
<beans>
<mvc:annotation-driven/>
<bean id="entityManagerFactoryBean" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.sms.examination.entity.*" />
</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/examination" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactoryBean" />
</bean>
<tx:annotation-driven/>
</beans>
NameDao Interface :-
package com.sms.examination.dao;
import java.util.List;
import com.sms.examination.entity.Name;
public interface NameDao {
public List<Name> findAll();
}
Implementation
package com.sms.examination.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.sms.examination.entity.Name;
#Repository
#Transactional
#Component
public class NamedaoImpl implements NameDao
{
#PrsistenceContext
private EntityManager entityManagerFactoryBean;
public List<Name> findAll() {
if(entityManagerFactoryBean==null)
{
System.out.println("manager is null");
}
else
System.out.println("manager is not null");
List<Name> names = entityManagerFactoryBean.createQuery("select s from Name s",Name.class).getResultList();
return names;
}
}
Controller
package com.sms.examination.controller;
import java.util.*;
import com.sms.examination.dao.NameDao;
import com.sms.examination.dao.NamedaoImpl;
import com.sms.examination.entity.Name;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class NameController {
#Autowired
private NameDao namedao;
#Autowired
private NamedaoImpl name;
public void getNames(){
List<Name> namelist=new ArrayList<Name>();
if(namedao==null)
{
System.out.println("name doa is null");
}
namelist=namedao.findAll();
Iterator<Name> it=namelist.iterator();
while(it.hasNext())
{
System.out.println(it.hasNext());
}
}
public static void main(String[] args) {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:application-context.xml");
NameController names=new NameController();
names.getNames();
}
}
While running the Controller class i am getting the below output.Please help
name doa is null which is because the NameDao class has not been initailised.
You need to add component scan in your application context
<context:component-scan base-package="com.sms.examination" />

Jersey API with Spring SessionFactory NullpointerException

Images of All Jars
This is the error image from the console.
I am trying to use the Jersey API along with Spring and Hibernate. However, defining session factory says NullPointerException. Can anybody help me to solve this? Added Full configuration with spring, hibernate and Jersey. Images of error and jar on top.
---------------------Dao Class:
package com.org.restservice.bo.user;
import java.util.List;
import com.org.restservice.common.Dao;
public interface AuthenticationDao extends Dao{
/*
* User Information List
*/
public List userInfo(AuthenticationVo authenticationVo) throws Exception;
}
---------------------DaoHibernate Class:
package com.org.restservice.bo.user;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.sql.DataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.type.StringType;
import org.springframework.orm.hibernate3.HibernateCallback;
import com.org.restservice.common.BaseDaoHibernate;
import com.org.restservice.common.Constant;
public class AuthenticationDaoHibernate extends BaseDaoHibernate implements AuthenticationDao{
private Log log = LogFactory.getLog(AuthenticationDaoHibernate.class);
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
/*
* User Information List
*/
public List userInfo(AuthenticationVo authenticationVo) throws Exception{
System.out.println("Called Me>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
List<AuthenticationVo> findlist = new ArrayList<AuthenticationVo>();
final String sqlQuery = "SELECT USER_ID, ROLE_ID from STTM_USER_MASTER";
System.out.println("sqlQuery: "+sqlQuery);
List results = (List) getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
SQLQuery sq = session.createSQLQuery(sqlQuery);
sq.addScalar("USER_ID", StringType.INSTANCE);
sq.addScalar("ROLE_ID", StringType.INSTANCE);
return sq.list();
}
});
try {
if (results.size() > 0) {
Iterator itr = results.iterator();
while (itr.hasNext()) {
authenticationVo = new AuthenticationVo();
Object[] row = (Object[]) itr.next();
authenticationVo.setUser_id((String) row[0]);
authenticationVo.setRole_id((String) row[1]);
findlist.add(authenticationVo);
}
}
} catch (Exception e) {
System.out.println("FunctonVos error:" + e.getMessage());
}
System.out.println("Size of User List is: "
+ findlist.size());
System.out.println("Procedure call ended.");
return findlist;
}
}
---------------------Facade Class:
package com.org.restservice.bo.user;
import java.util.List;
import com.org.restservice.common.Facade;
public interface AuthenticationFacade extends Facade{
public void setAuthenticationDao(AuthenticationDao authenticationDao);
/*
* User Information List
*/
public List userInfo(AuthenticationVo authenticationVo) throws Exception;
}
---------------------FacadeImpl Class:
package com.org.restservice.bo.user;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.org.restservice.common.BaseFacade;
public class AuthenticationFacadeImpl extends BaseFacade implements AuthenticationFacade{
private static final Log log = LogFactory.getLog(AuthenticationFacadeImpl.class);
private AuthenticationDao authenticationDao;
public void setAuthenticationDao(AuthenticationDao authenticationDao) {
this.authenticationDao = authenticationDao;
}
/*
* User Information List
*/
public List userInfo(AuthenticationVo authenticationVo) throws Exception{
return authenticationDao.userInfo(authenticationVo);
}
}
---------------------Business Object Class:
package com.org.restservice.bo.user;
import com.org.restservice.common.BaseObject;
public class AuthenticationVo extends BaseObject{
private static final long serialVersionUID = 1L;
private String user_id;
private String role_id;
public AuthenticationVo(String user_id, String role_id) {
super();
this.user_id = user_id;
this.role_id = role_id;
}
public AuthenticationVo() {
super();
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getRole_id() {
return role_id;
}
public void setRole_id(String role_id) {
this.role_id = role_id;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((role_id == null) ? 0 : role_id.hashCode());
result = prime * result + ((user_id == null) ? 0 : user_id.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AuthenticationVo other = (AuthenticationVo) obj;
if (role_id == null) {
if (other.role_id != null)
return false;
} else if (!role_id.equals(other.role_id))
return false;
if (user_id == null) {
if (other.user_id != null)
return false;
} else if (!user_id.equals(other.user_id))
return false;
return true;
}
#Override
public String toString() {
return "AuthenticationVo [user_id=" + user_id + ", role_id=" + role_id + "]";
}
}
---------------------Action Class Declaration:
package com.org.restservice.portal.user;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.org.restservice.bo.user.AuthenticationFacade;
import com.org.restservice.bo.user.AuthenticationVo;
#Path("userService")
public class UserAction{
private final Log log = LogFactory.getLog(UserAction.class);
AuthenticationVo authenticationVo = new AuthenticationVo();
private AuthenticationFacade authenticationFacade = null;
private List<AuthenticationVo> listofUsers = new ArrayList<AuthenticationVo>();
public AuthenticationVo getAuthenticationVo() {
return authenticationVo;
}
public void setAuthenticationVo(AuthenticationVo authenticationVo) {
this.authenticationVo = authenticationVo;
}
public AuthenticationFacade getAuthenticationFacade() {
return authenticationFacade;
}
public void setAuthenticationFacade(AuthenticationFacade authenticationFacade) {
this.authenticationFacade = authenticationFacade;
}
public List<AuthenticationVo> getListofUsers() {
return listofUsers;
}
public void setListofUsers(List<AuthenticationVo> listofUsers) {
this.listofUsers = listofUsers;
}
#GET
#Produces( "application/json" )
public List<AuthenticationVo> customAction(){
if (log.isDebugEnabled()) {
log.debug("Entering into loadusers Method of AuthenticationAction: " +authenticationFacade);
}
try {
listofUsers = authenticationFacade.userInfo(authenticationVo);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(">>>>>>>>>>>>>>>>>>>>>" +listofUsers.size());
/*authenticationVo.setUser_id("1234");
authenticationVo.setRole_id("134352");
listofUsers.add(authenticationVo);*/
return listofUsers;
}
}
---------------------Spring Beans Declaration:
<!-- <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.xsd"> -->
<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.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-3.0.xsd">
<!-- Database connection using jndi properties-->
<import resource="config/applicationContext-jndi.xml"/>
<import resource="config/applicationContext.xml"/>
<!-- List and Setup -->
<import resource="config/applicationContext-auth.xml"/>
</beans>
---------------------Application Context Declaration:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
<list>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.hbm2ddl.auto">validate</prop>
<prop key="hibernate.query.factory_class">org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory</prop>
</props>
</property>
</bean>
<!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<!-- Transaction template for Facade -->
<bean id="txProxyTemplate" abstract="true"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager">
<ref bean="transactionManager"/>
</property>
<property name="transactionAttributes">
<props>
<prop key="save*">PROPAGATION_REQUIRED</prop>
<prop key="remove*">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>
<!-- DAO bean -->
<!-- Generic DAO - can be used when doing standard CRUD -->
<bean id="dao" class="com.org.restservice.common.BaseDaoHibernate">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
<property name="dataSource" ref="dataSource" />
</bean>
<!-- Generic Facade that can be used to do basic CRUD operations on any
objects -->
<bean id="facade" parent="txProxyTemplate">
<property name="target">
<bean class="com.org.restservice.common.BaseFacade">
<property name="Dao" ref="dao" />
</bean>
</property>
</bean>
</beans>
--------------------- Context Declaration:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!-- Transaction declarations for business services. -->
<bean id="authenticationFacade" parent="txProxyTemplate">
<property name="target">
<bean
class="com.org.restservice.bo.user.AuthenticationFacadeImpl">
<property name="authenticationDao">
<ref bean="authenticationDao" />
</property>
</bean>
</property>
</bean>
<!-- authenticationDao: Hibernate implementation -->
<bean id="authenticationDao"
class="com.org.restservice.bo.user.AuthenticationDaoHibernate">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
<property name="dataSource">
<ref bean="dataSource" />
</property>
</bean>
</beans>
---------------------Jndi Declaration:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<!-- author: Sarkar Zahir Ahamed <ahamed.sarkar#dbbl.com.bd> -->
<beans>
<!-- ========================= PERSISTENCE DEFINITIONS ========================= -->
<!-- JNDI DataSource for J2EE environments -->
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>java:/comp/env/jndi/orcl</value>
</property>
</bean>
</beans>
---------------------Web XML Declaration:
<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>RestWebService</display-name>
<!-- Spring Listener -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Jersey Servlet -->
<servlet>
<servlet-name>jersey-servlet</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<!-- Register resources and providers -->
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.org.restservice</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-servlet</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
<!-- loading Spring Context for registering beans with ApplicationContext -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/classes/SpringBeans.xml</param-value>
</context-param>
<!-- welcome file -->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

how to convert xml notation to annotation based notation : Spring - Java

I have following xml configuration in my spring context xml, I have used annotation based approach very less and unable to figure out how to represent following using annotation, need help.
<bean id="myPolicyAdmin" class="org.springframework.security.oauth2.client.OAuth2RestTemplate">
<constructor-arg>
<bean class="org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails">
<property name="accessTokenUri" value="${accessTokenEndpointUrl}" />
<property name="clientId" value="${clientId}" />
<property name="clientSecret" value="${clientSecret}" />
<property name="username" value="${policyAdminUserName}" />
<property name="password" value="${policyAdminUserPassword}" />
</bean>
</constructor-arg>
</bean>
In my java class(Policy manager) it is referred as following, I am actually referring a sample and trying to convert it all annotation baesed.
#Autowired
#Qualifier("myPolicyAdmin")
private OAuth2RestTemplate myPolicyAdminTemplate;
EDIT:
I tried creating a bean for org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails but not sure how to set its properties and how to access it as constructor args to myPolicyAdminTemplate
You can configure the same beans using JavaConfig as follows:
#Component
#Configuration
public class AppConfig
{
#Value("${accessTokenEndpointUrl}") String accessTokenUri;
#Value("${clientId}") String clientId;
#Value("${clientSecret}") String clientSecret;
#Value("${policyAdminUserName}") String username;
#Value("${policyAdminUserPassword}") String password;
#Bean
public OAuth2RestTemplate myPolicyAdmin(ResourceOwnerPasswordResourceDetails details)
{
return new OAuth2RestTemplate(details);
}
#Bean
public ResourceOwnerPasswordResourceDetails resourceOwnerPasswordResourceDetails()
{
ResourceOwnerPasswordResourceDetails bean = new ResourceOwnerPasswordResourceDetails();
bean.setAccessTokenUri(accessTokenUri);
bean.setClientId(clientId);
bean.setClientSecret(clientSecret);
bean.setUsername(username);
bean.setPassword(password);
return bean;
}
}
To set the props of a bean you can either use #Value during construction:
How to inject a value to bean constructor using annotations
and this one:
Spring: constructor injection of primitive values (properties) with annotation based configuration
Or #Value in the variables. You could also actually use #Resource, but I wouldn't recommend it.
In your case, the constructor for the
org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails
Would be kinda like
#Autowired
public ResourceOwnerPasswordResourceDetails(
#Value("${accessTokenEndpointUrl}") String accessTokenUri,
#Value("${clientId}") String clientId,
#Value("${clientSecret}") String clientSecret,
#Value("${policyAdminUserName}") String username,
#Value("${policyAdminUserPassword}") String password
)
I shall give you a XML configuration with it anotation based config equivalent respectively, so that you will easily see how to change your bean from xml to java and vice-versa
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:component-scan base-package="com.mycompany.backendhibernatejpa.controller" />
<mvc:annotation-driven />
<bean id="iAbonneDao" class="com.mycompany.backendhibernatejpa.daoImpl.AbonneDaoImpl"/>
<bean id="iAbonneService" class="com.mycompany.backendhibernatejpa.serviceImpl.AbonneServiceImpl"/>
<!-- couche de persistance JPA -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
<property name="generateDdl" value="true" />
<property name="showSql" value="true" />
</bean>
</property>
<property name="loadTimeWeaver">
<bean
class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
</bean>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath:bd.properties"/>
</bean>
<!-- la source de donnéees DBCP -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" >
<property name="driverClassName" value="${bd.driver}" />
<property name="url" value="${bd.url}" />
<property name="username" value="${bd.username}" />
<property name="password" value="${bd.password}" />
</bean>
<!-- le gestionnaire de transactions -->
<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- traduction des exceptions -->
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<!-- annotations de persistance -->
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
</beans>
this file is named springrest-sevlet. actually you can give the name you want followed by "-servlet" and mention that name in the file web.xml
<web-app>
<display-name>Gescable</display-name>
<servlet>
<servlet-name>springrest</servlet-name>
<servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springrest</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
the two files should be place in the folder "WEB-INF".
Now the equivalent with anotation based config
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.backendhibernatejpaannotation.configuration;
import com.mycompany.backendhibernatejpaannotation.daoImpl.AbonneDaoImpl;
import com.mycompany.backendhibernatejpaannotation.daoInterface.IAbonneDao;
import com.mycompany.backendhibernatejpaannotation.serviceImpl.AbonneServiceImpl;
import com.mycompany.backendhibernatejpaannotation.serviceInterface.IAbonneService;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
/**
*
* #author vivien saa
*/
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.mycompany.backendhibernatejpaannotation")
public class RestConfiguration {
#Bean
public IAbonneDao iAbonneDao() {
return new AbonneDaoImpl();
}
#Bean
public IAbonneService iAbonneService() {
return new AbonneServiceImpl();
}
// #Bean
// public PropertyPlaceholderConfigurer placeholderConfigurer() {
// PropertyPlaceholderConfigurer placeholderConfigurer = new PropertyPlaceholderConfigurer();
// placeholderConfigurer.setLocations("classpath:bd.properties");
// return placeholderConfigurer;
// }
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/gescable");
dataSource.setUsername("root");
dataSource.setPassword("root");
return dataSource;
}
#Bean
public HibernateJpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
jpaVendorAdapter.setDatabasePlatform("org.hibernate.dialect.MySQL5InnoDBDialect");
jpaVendorAdapter.setGenerateDdl(true);
jpaVendorAdapter.setShowSql(true);
return jpaVendorAdapter;
}
#Bean
public InstrumentationLoadTimeWeaver loadTimeWeaver() {
InstrumentationLoadTimeWeaver loadTimeWeaver = new InstrumentationLoadTimeWeaver();
return loadTimeWeaver;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
entityManagerFactory.setDataSource(dataSource());
entityManagerFactory.setJpaVendorAdapter(jpaVendorAdapter());
entityManagerFactory.setLoadTimeWeaver(loadTimeWeaver());
return entityManagerFactory;
}
#Bean
public JpaTransactionManager jpaTransactionManager() {
JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
jpaTransactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return jpaTransactionManager;
}
#Bean
public PersistenceExceptionTranslationPostPro`enter code here`cessor persistenceExceptionTranslationPostProcessor() {
return new PersistenceExceptionTranslationPostProcessor();
}
#Bean
public PersistenceAnnotationBeanPostProcessor persistenceAnnotationBeanPostProcessor() {
return new PersistenceAnnotationBeanPostProcessor();
}
}
this file must be accompanied by this one
package com.mycompany.backendhibernatejpaannotation.configuration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
/**
*
* #author vivien saa
*/
public class Initializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{RestConfiguration.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}

spring3 - application context - bean property name and reference - null pointer exception

All - In the Spring 3.0, in the applicationContext.xml .... are we supposed to have the bean property name and the reference value to be the same ? If I give a different value, it returns null object. But on giving the same value, it works. For my project, i am supposed to give different values for them. Kindly help. bye, HS
This works: (same values)
<bean id="MNCWIRAdminBaseAction" class="com.megasoft.wiradmin.web.action.WIRAdminBaseAction">
<property name="cacheDelegate">
<ref bean="cacheDelegate" />
</property>
</bean>
This doesn't work: (different values)
<bean id="MNCWIRAdminBaseAction" class="com.megasoft.wiradmin.web.action.WIRAdminBaseAction">
<property name="cacheDelegate">
<ref bean="MNCCacheDelegate" />
</property>
</bean>
bye, HS
My Full Code here:
WIRAdminBaseAction.java ---> my base action
AuthenticateAction.java ---> my java file that calls the bean here
applicationContext.xml --> system's applicationcontext file
applicationContext_MNC.xml ---> my applicationContext for a specific company ... this is getting loaded by my java file, which gets invoked by the web.xml file.
CacheDelegate.java
StatusDBDAO.java
PreXMLWebApplicationContext.java ----> loads my applicationContext file for the specific company.
****** 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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
<bean name="exceptionHandler" class="com.megasoft.wir.eStatement.web.interceptor.WIRExceptionHandlerInterceptor"/>
<bean name="security" class="com.megasoft.wir.eStatement.web.interceptor.SecurityInterceptor"/>
<bean name="permission" class="com.megasoft.wir.eStatement.web.interceptor.PermissionInterceptor"/>
<!-- AutoProxies -->
<bean name="loggingAutoProxy" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property name="interceptorNames">
<list>
<value>base</value>
<value>exceptionHandler</value>
<value>security</value>
<value>permission</value>
</list>
</property>
</bean>
</beans>
****** applicationContext_MNC.xml ******
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="MNCWIRAdminBaseAction" class="com.megasoft.wiradmin.web.action.WIRAdminBaseAction">
<property name="cacheDelegate">
<ref bean="MNCCacheDelegate" />
</property>
</bean>
<bean id="MNCCacheDelegate" class="com.megasoft.wiradmin.delegate.CacheDelegate" >
<property name="statusDBDAO"><ref bean="MNCStatusDBDAO" /></property>
</bean>
<bean id="MNCStatusDBDAO" class="com.megasoft.wiradmin.dao.StatusDBDAO">
<property name="dataSource">
<ref bean="MNCAdminDataSource" />
</property>
</bean>
<!-- database configuration from property file -->
<bean id="MNCAdminDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close" lazy-init="default" autowire="default" dependency-check="default">
<property name="driverClass" value="${jdbc.driver}" ></property>
<property name="jdbcUrl" value="${admin.jdbc.url}" ></property>
<property name="user" value="${admin.jdbc.user}" ></property>
<property name="password" value="${admin.jdbc.password}" ></property>
<property name="initialPoolSize" value="3" ></property>
<property name="minPoolSize" value="3" ></property>
<property name="maxPoolSize" value="25" ></property>
<property name="acquireIncrement" value="1" ></property>
<property name="acquireRetryDelay" value="1000" ></property>
<property name="debugUnreturnedConnectionStackTraces" value="true" ></property>
<property name="maxIdleTime" value="300" ></property>
<property name="unreturnedConnectionTimeout" value="300000" ></property>
<property name="preferredTestQuery" value="SELECT COUNT(*) FROM LOCALE_CODE" ></property>
<property name="checkoutTimeout" value="300000" ></property>
<property name="idleConnectionTestPeriod" value="600000" ></property>
</bean>
<!-- this bean is set to map the constants which needs to be configured as per
the environment to the java constants file -->
<bean id="envConstantsConfigbean" class="com.megasoft.wiradmin.util.constants.Environm entConstantsSetter">
<property name="loginUrl" value="${login.url}"/>
<property name="logoutIR" value="${logout.from.image.retrieval}"/>
<property name="adminModuleUrl" value="${admin.url}"/>
<property name="adminUrlSym" value="${admin.url.sym}"/>
<property name="envProperty" value="${env.property}"/>
</bean>
</beans>
****** AuthenticateAction.java ******
package com.megasoft.wiradmin.web.action;
import java.net.UnknownHostException;
import java.sql.SQLException;
import org.bouncycastle.crypto.CryptoException;
import org.springframework.context.ApplicationContext;
import org.springframework.dao.DataAccessException;
import org.springframework.web.context.support.WebApplica tionContextUtils;
import com.megasoft.wiradmin.delegate.ICacheDelegate;
public class AuthenticateAction extends WIRAdminBaseAction {
private static final long serialVersionUID = 1L;
public String authenticate() throws UnknownHostException, CryptoException,
DataAccessException, SQLException{
/** This way of calling works...... This is not encouraged, as we should not use applicationContext always **/
ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContex t(getServletRequest().getSession().getServletConte xt());
ICacheDelegate cacheAction = (ICacheDelegate) applicationContext.getBean("MNCCacheDelegate");
/** The below way of calling does NOT work .... returns null value.... Please help...
* I assume that, since I have extended the WIRAdminBaseAction, i should be able to call the getCacheDelegate directly
* and it should return my cacheDelegate object ...
* Again, Please note.....if I change my applicationContext_MNC.xml as below, the below way of calling works fine...
* but, i don't want to change my applicationContext_MNC.xml as below, due to some necessity.
*
<bean id="MNCWIRAdminBaseAction" class="com.megasoft.wiradmin.web.action.WIRAdminBaseAction">
<property name="cacheDelegate">
<ref bean="cacheDelegate" />
</property>
</bean>
*
<bean id="cacheDelegate" class="com.megasoft.wiradmin.delegate.CacheDelegate" >
<property name="statusDBDAO"><ref bean="MNCStatusDBDAO" /></property>
</bean>
*
... is it that the name and bean should have the same value.... ??? No Need to be.....Am i right ? Please advise.
*
* **/
getCacheDelegate().getActorAction(1); // this way of calling doesn't work and returns null value. please help.
return "success";
}
}
****** WIRAdminBaseAction.java ******
package com.megasoft.wiradmin.web.action;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.interceptor.ParameterAware;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.opensymphony.xwork2.config.entities.Parameteri zable;
import com.megasoft.wiradmin.delegate.ICacheDelegate;
public class WIRAdminBaseAction extends ActionSupport implements Preparable, ParameterAware, Parameterizable, SessionAware,RequestAware {
private HttpServletRequest request;
private static final long serialVersionUID = 1L;
private HttpServletResponse response;
private ICacheDelegate cacheDelegate;
private Map session;
private Map<String, String> params;
private Map parameters;
public void prepare() throws Exception {
}
public String execute() throws Exception {
return SUCCESS;
}
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
public HttpServletRequest getServletRequest() {
return this.request;
}
public void setServletResponse(HttpServletResponse response) {
this.response = response;
}
public HttpServletResponse getServletResponse() {
return this.response;
}
public ICacheDelegate getCacheDelegate() {
return cacheDelegate;
}
public void setCacheDelegate(ICacheDelegate cacheDelegate) {
this.cacheDelegate = cacheDelegate;
}
public void addParam(final String key, final String value) {
this.params.put(key, value);
}
public Map getParams() {
return params;
}
public void setParams(final Map<String, String> params) {
this.params = params;
}
public Map getSession() {
return this.session;
}
public void setSession(final Map session) {
this.session = session;
}
public void setParameters(final Map param) {
this.parameters = param;
}
}
PreXMLWebApplicationContext.java **
package com.megasoft.wiradmin.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.support.XmlWebApplicationContext;
public class PreXMLWebApplicationContext extends XmlWebApplicationContext {
/**
* This initializes the Logger.
*/
private static Log logger = LogFactory.getLog(PreXMLWebApplicationContext.class);
protected String[] getDefaultConfigLocations() {
String environment = System.getProperty("envProperty");
String webirConfig = System.getProperty("webirConfig");
String fi = System.getProperty("FI");
String preHostConfiguration =null;
logger.info("The environment is "+environment);
logger.info("The webirConfig is "+webirConfig);
logger.info("The fi is "+fi);
if(environment != null && webirConfig != null && fi != null) {
preHostConfiguration = DEFAULT_CONFIG_LOCATION_PREFIX +
"classes/applicationContext" + "_" + fi.toUpperCase() +
DEFAULT_CONFIG_LOCATION_SUFFIX;
}
return new String[]{DEFAULT_CONFIG_LOCATION, preHostConfiguration};
}
/**
* This is close API.
*
* #see org.springframework.context.support.AbstractApplicationContext
* #close()
*/
public void close() {
this.doClose();
logger.info("Login-->into the closed");
}
}
<property name="userDelegate" ref="userDelegate" />
name is the field name in your class. When name is userDelegate, it means that WIRAdminBaseAction has a field named userDelegate (and probably a setter setUserDelegate())
ref is the bean name you want to set this field to. In your example, you should have another bean, named userDelegate or bmoUserDelegate which should be set as userDelegate in WIRAdminBaseAction.
So if you want to use the second configuration:
You just need to create a bean with id bmoUserDelegate:
<bean id="bmoUserDelegate" class="mypackage.BmoUserDelegateClass"/>

Vaadin with Spring and Multiple Users

I have a really strange Problem with my new Vaadin Project.
If I start my Application and log in with a User, then switch the Browser and open the Site again, it seems that the Sessions will be shared. I have the same Content in both Windows.
I readed a few forum Posts about this Problem, all they say don´t open the App in the same Browser. Ok, i startet a VM, but, the same Problem. Or, remove all static variables from the context. I have done that, now using the ThreadLocal-Pattern.
I have absolutly no idea whats wrong. What I believe is that the Spring Context kills Vaadin, has anyone ever had this experience with Vaadin and Spring?
To bring Spring and Vaadin togehter I use the Spring Intgration Addon for Vaadin by Nicolas Frankel (https://vaadin.com/directory#addon/spring-integration)
I will post my Application Code for further investigation.
===================
The Vaadin Application Class:
public class MainApplication extends Application implements HttpServletRequestListener {
private static final long serialVersionUID = 2067470624065324231L;
private static ThreadLocal<MainApplication> threadLocal = new ThreadLocal<MainApplication>();
private Window mainWindow;
//Viewmanager
private ViewManager viewManager;
private Professor professor;
//DAO Classes and Bean Setter´s
ProfessorDAO professorDAO;
QuestionDAO questionDAO;
AnswerDAO answerDAO;
AnsweredDAO answeredDAO;
QRCodeDAO qrCodeDAO;
public void setProfessorDAO(ProfessorDAO professorDAO) {
System.out.println("Setting ProfessorDAO!");
System.out.println(professorDAO.toString());
this.professorDAO = professorDAO;
}
public void setQuestionDAO(QuestionDAO questionDAO) {
System.out.println("Setting QuestionDAO!");
System.out.println(questionDAO.toString());
this.questionDAO = questionDAO;
}
public void setAnswerDAO(AnswerDAO answerDAO) {
System.out.println("Setting AnswerDAO!");
System.out.println(answerDAO.toString());
this.answerDAO = answerDAO;
}
public void setAnsweredDAO(AnsweredDAO answeredDAO) {
System.out.println("Setting AnsweredDAO!");
System.out.println(answeredDAO.toString());
this.answeredDAO = answeredDAO;
}
public void setQrCodeDAO(QRCodeDAO qrCodeDAO) {
System.out.println("Setting QRCodeDAO!");
System.out.println(qrCodeDAO.toString());
this.qrCodeDAO = qrCodeDAO;
}
public ProfessorDAO getProfessorDAO() {
return professorDAO;
}
public QuestionDAO getQuestionDAO() {
return questionDAO;
}
public AnswerDAO getAnswerDAO() {
return answerDAO;
}
public AnsweredDAO getAnsweredDAO() {
return answeredDAO;
}
public QRCodeDAO getQrCodeDAO() {
return qrCodeDAO;
}
//Currently logged in Professor.
public Professor getProfessor() {
return professor;
}
public void setProfessor(Professor professor) {
this.professor = professor;
}
public static void setInstance(MainApplication application){
threadLocal.set(application);
}
public ViewManager getViewManager() {
return viewManager;
}
public void setViewManager(ViewManager viewManager) {
this.viewManager = viewManager;
}
public static MainApplication getInstance(){
return threadLocal.get();
}
public MainApplication() {
}
#Override
public void init() {
setInstance(this);
setTheme("crs");
mainWindow = new Window("CRS -- Classroom Response System");
setMainWindow(mainWindow);
viewManager = new ViewManager(mainWindow);
viewManager.switchScreen(LoginScreen.class.getName(), new LoginScreen());
//mainWindow = new MainWindow("CRS -- Classroom Response System");
//setMainWindow(mainWindow);
}
public void onRequestStart(HttpServletRequest request,
HttpServletResponse response) {
MainApplication.setInstance(this);
}
public void onRequestEnd(HttpServletRequest request,
HttpServletResponse response) {
threadLocal.remove();
}
The web.xml:
<display-name>CRSServer</display-name>
<context-param>
<description>
Vaadin production mode</description>
<param-name>productionMode</param-name>
<param-value>false</param-value>
</context-param>
<servlet>
<servlet-name>CRS</servlet-name>
<servlet-class>ch.frankel.vaadin.spring.SpringApplicationServlet</servlet-class>
<init-param>
<description>
Vaadin application class to start</description>
<param-name>applicationBeanName</param-name>
<param-value>cs.hm.edu.kreipl.crs.frontend.MainApplication</param-value>
</init-param>
<init-param>
<description>
Application widgetset</description>
<param-name>widgetset</param-name>
<param-value>cs.hm.edu.kreipl.crs.widgetset.CrsserverWidgetset</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>CRS</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/spring-config.xml</param-value>
</context-param>
The Spring Context
<context:component-scan base-package="cs.hm.edu.kreipl.crs" />
<bean id="myDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="com.mysql.jdbc.Driver">
</property>
<property name="url" value="jdbc:mysql://localhost:3306/crs"></property>
<property name="username" value="crs"></property>
<property name="password" value="password"></property>
</bean>
<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="annotatedClasses">
<list>
<value>cs.hm.edu.kreipl.crs.database.entity.Professor</value>
<value>cs.hm.edu.kreipl.crs.database.entity.Answer</value>
<value>cs.hm.edu.kreipl.crs.database.entity.Answered</value>
<value>cs.hm.edu.kreipl.crs.database.entity.Question</value>
<value>cs.hm.edu.kreipl.crs.database.entity.QuestionQRCode</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="mySessionFactory" />
</bean>
<tx:annotation-driven/>
<!-- VAADIn Startup -->
<bean id="cs.hm.edu.kreipl.crs.frontend.MainApplication" class="cs.hm.edu.kreipl.crs.frontend.MainApplication">
<property name="answerDAO" ref="answerDAO" />
<property name="answeredDAO" ref="answeredDAO" />
<property name="professorDAO" ref="professorDAO" />
<property name="qrCodeDAO" ref="qrCodeDAO" />
<property name="questionDAO" ref="questionDAO" />
</bean>
<bean id="professorDAO" class="cs.hm.edu.kreipl.crs.database.implementation.ProfessorDAOImpl">
<constructor-arg>
<value>cs.hm.edu.kreipl.crs.database.entity.Professor</value>
</constructor-arg>
<property name="hibernateTemplate" ref="mySessionFactory"/>
</bean>
<bean id="questionDAO" class="cs.hm.edu.kreipl.crs.database.implementation.QuestionDAOImpl">
<constructor-arg>
<value>cs.hm.edu.kreipl.crs.database.entity.Question</value>
</constructor-arg>
<property name="hibernateTemplate" ref="mySessionFactory"/>
</bean>
<bean id="qrCodeDAO" class="cs.hm.edu.kreipl.crs.database.implementation.QRCodeDAOImpl">
<constructor-arg>
<value>cs.hm.edu.kreipl.crs.database.entity.QuestionQRCode</value>
</constructor-arg>
<property name="hibernateTemplate" ref="mySessionFactory"/>
</bean>
<bean id="answerDAO" class="cs.hm.edu.kreipl.crs.database.implementation.AnswerDAOImpl">
<constructor-arg>
<value>cs.hm.edu.kreipl.crs.database.entity.Answer</value>
</constructor-arg>
<property name="hibernateTemplate" ref="mySessionFactory"/>
</bean>
<bean id="answeredDAO" class="cs.hm.edu.kreipl.crs.database.implementation.AnsweredDAOImpl">
<constructor-arg>
<value>cs.hm.edu.kreipl.crs.database.entity.Answered</value>
</constructor-arg>
<property name="hibernateTemplate" ref="mySessionFactory"/>
</bean>
<bean id="deviceDAO" class="cs.hm.edu.kreipl.crs.database.implementation.DeviceDAOImpl">
<constructor-arg>
<value>cs.hm.edu.kreipl.crs.database.entity.Device</value>
</constructor-arg>
<property name="hibernateTemplate" ref="mySessionFactory"/>
</bean>
If you need any further classes please let me now.
I am using Vaadin + Spring but without Spring Integration Addon.
I think that the problem is that you are not creating a new Vaadin applicationBean for the new user that requests the application.
In my app, I pass the applicationBean in web.xml. My Vaadin application is annotated with:
Application Class
#Component(value = "appName")
#Scope(value = "session")
class AppName extends Application {
....
}
WEB.XML
<init-param>
<param-name>applicationBean</param-name>
<param-value>appName</param-value>
</init-param>
And for every new session Servlet returns new app.
In your web.xml you pass your vaadin application like this:
Your WEB.XML
<init-param>
<description>
Vaadin application class to start</description>
<param-name>applicationBeanName</param-name>
<param-value>cs.hm.edu.kreipl.crs.frontend.MainApplication</param-value>
</init-param>
So it returns every time the same app for all users. And that's what I think causes the problem.

Categories