a Failed IOC Injection - Spring and JSF integration - spring

I'm trying to integrate jsf with spring and
inject service classes on my managed bean
My managed bean:
package web;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.faces.bean.ManagedBean;
import mapping.*;
import gestion.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
#Component
#ManagedBean(name="bean")
#SessionScoped
public class AjoutChamp {
private Module module;
private int m;
private int etape;
private int menu;
private int TypeChamp;
private int action;
private int selecteur;
private String valeur_selecteur;
private String contexte;
private String texte;
#Autowired
private GestionEtape gEtape;
#Autowired
private GestionModule gModule;
private List<Module> listeModule;
#PostConstruct
void init(){
listeModule=gModule.selectAll();
}
public int getM() {
return m;
}
public void setM(int m) {
this.m = m;
}
public List<Module> getListeModule() {
return listeModule;
}
public void setListeModule(List<Module> listeModule) {
this.listeModule = listeModule;
}
public GestionEtape getgEtape() {
return gEtape;
}
public void setgEtape(GestionEtape gEtape) {
this.gEtape = gEtape;
}
public GestionModule getgModule() {
return gModule;
}
public void setgModule(GestionModule gModule) {
this.gModule = gModule;
}
public Module getModule() {
return module;
}
public void setModule(Module module) {
this.module = module;
}
public int getEtape() {
return etape;
}
public void setEtape(int etape) {
this.etape = etape;
}
public int getMenu() {
return menu;
}
public void setMenu(int menu) {
this.menu = menu;
}
public int getTypeChamp() {
return TypeChamp;
}
public void setTypeChamp(int typeChamp) {
TypeChamp = typeChamp;
}
public int getAction() {
return action;
}
public void setAction(int action) {
this.action = action;
}
public int getSelecteur() {
return selecteur;
}
public void setSelecteur(int selecteur) {
this.selecteur = selecteur;
}
public String getValeur_selecteur() {
return valeur_selecteur;
}
public void setValeur_selecteur(String valeur_selecteur) {
this.valeur_selecteur = valeur_selecteur;
}
public String getContexte() {
return contexte;
}
public void setContexte(String contexte) {
this.contexte = contexte;
}
public String getTexte() {
return texte;
}
public void setTexte(String texte) {
this.texte = texte;
}
public AjoutChamp(){}
}
my applicationContext:
<?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"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="web"></context:component-scan>
<context:component-scan base-package="dao"></context:component-scan>
<context:component-scan base-package="gestion"></context:component-scan>
<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/yo?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</bean>
<bean id="factory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<props>
<prop
key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>mapping</value>
</list>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="factory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

Add the following to your applicationContext.xml:
xmlns:context="http://www.springframework.org/schema/context"
and
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
So, your applicationContext.xml should look like this.
<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"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
...
</beans>
Add the spring-context library to your project too.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version><!-- version of Spring context. --></version>
</dependency>
If you're using Maven.

Wrong combination
import javax.enterprise.context.SessionScoped;
import javax.faces.bean.ManagedBean;
Weird combination
#Component
#ManagedBean(name="bean")
#SessionScoped
Both have all been discussed in Stackoverflow.

Related

No bean named '##' is defined serverless framework Spring

I have this problem, I'm working with Spring, Hibernate, JPA and serverless framework.
When I invoke the class form the console I got this error "
"errorMessage": "No bean named 'wizardDao' is defined",
"errorType": "org.springframework.beans.factory.NoSuchBeanDefinitionException",
"stackTrace": [
"org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:694)",
"org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1168)",
"org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:281)",
"org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)",
"org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:956)",
"com.serverless.dao.Handler.handleRequest(Handler.java:30)",
"com.serverless.dao.Handler.handleRequest(Handler.java:17)"
but if I prove the class in Eclipse with I main class there's not problema. I don't know what is going wrong
this is my applicationContext
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">
<context:component-scan base-package="com.serverless" />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="Things-serverless" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<task:scheduler id="taskScheduler" />
<task:executor id="taskExecutor" pool-size="1" />
<task:annotation-driven executor="taskExecutor"
scheduler="taskScheduler" />
<!-- <bean id="serviceBean" class="com.serverless.test" /> -->
</beans>
this is my dao class
#Component
public class WizardDao extends ForwardedMessageDao {
private static final long serialVersionUID = 5302145657830590489L;
/**
* Get all wizards from data base.
*
* #param
* #return List of wizards
*/
#SuppressWarnings("unchecked")
public List<Wizard> getAllWizards() {
Query query = getEmf().createQuery("FROM Wizard");
System.out.println("aqui ");
return (List<Wizard>) query.getResultList();
}
}
and this is my handdler class
#Service
#Transactional
public class Handler implements RequestHandler<Map<String, Object>, ApiGatewayResponse> {
private static final Logger LOG = Logger.getLogger(Handler.class);
#Autowired
private WizardDao wizardDao;
#Override
public ApiGatewayResponse handleRequest(Map<String, Object> input, Context context) {
BasicConfigurator.configure();
Map<String, Wizard> response = new HashMap<>();
Response responseBody = new Response("start", response);
try {
wizardDao = Application.getBean(WizardDao.class);
List<Wizard> listWizard = wizardDao.getAllWizards();
for (Wizard wizard : listWizard) {
response.put("" + wizard.getIdWizard(), wizard);
}
responseBody.setInput(response);
} catch (Exception e) {
responseBody.setMessage("Fail: " + e.getMessage());
}
LOG.info("received: " + input);
return ApiGatewayResponse.builder().setStatusCode(200).setObjectBody(responseBody)
.setHeaders(Collections.singletonMap("fur", "this sheep")).build();
}
}
and this is my entityManager Class
public class EntityManagerDao implements Serializable {
private static final long serialVersionUID = -6969245506190987187L;
#PersistenceContext(unitName = "Things-serverless")
private EntityManager em;
/**
* #return the em
*/
public EntityManager getEmf() {
return em;
}
}

How to perform Hsqldb SET Operation dynamically in Spring

We are using HSQL Database Engine 2.3.2 with Spring 4.1.0.RELEASE while my spring configuration is as following:
Here is applicationContext.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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx" 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-4.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
<bean class="com.chorke.spring.bootstarp.HyperSqlDbServer" id="hsqldb" init-method="start">
<constructor-arg>
<props>
<prop key="server.port">9002</prop>
<prop key="server.dbname.0">chorke</prop>
<prop key="server.remote_open">true</prop>
<prop key="server.database.0">file:~/.hsqldb/chorke/data;sql.syntax_mys=true;user=admin;password=pa55word</prop>
<prop key="hsqldb.default_table_type">text</prop>
<prop key="hsqldb.reconfig_logging">false</prop>
</props>
</constructor-arg>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.hsqldb.jdbc.JDBCDriver" />
<property name="url" value="jdbc:hsqldb:hsql://localhost:9002/chorke" />
<property name="username" value="admin" />
<property name="password" value="pa55word" />
</bean>
<jdbc:initialize-database data-source="dataSource">
<jdbc:script location="classpath:schema.sql"/>
<jdbc:script location="classpath:data.sql"/>
</jdbc:initialize-database>
</beans>
Here is com.chorke.spring.bootstarp.HyperSqlDbServer
package com.chorke.spring.bootstarp;
import java.io.IOException;
import java.util.Properties;
import org.hsqldb.Server;
import org.hsqldb.persist.HsqlProperties;
import org.hsqldb.server.ServerAcl.AclFormatException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.SmartLifecycle;
public class HyperSqlDbServer implements SmartLifecycle {
private final Logger logger = LoggerFactory.getLogger(HyperSqlDbServer.class);
private HsqlProperties properties;
private Server server;
private boolean running = false;
public HyperSqlDbServer(Properties props) {
properties = new HsqlProperties(props);
}
#Override
public boolean isRunning() {
if (server != null)
server.checkRunning(running);
return running;
}
#Override
public void start() {
if (server == null) {
logger.info("Starting HSQL server...");
server = new Server();
try {
server.setProperties(properties);
server.start();
running = true;
} catch (AclFormatException afe) {
logger.error("Error starting HSQL server.", afe);
} catch (IOException e) {
logger.error("Error starting HSQL server.", e);
}
}
}
#Override
public void stop() {
logger.info("Stopping HSQL server...");
if (server != null) {
server.stop();
running = false;
}
}
#Override
public int getPhase() {
return 0;
}
#Override
public boolean isAutoStartup() {
return true;
}
#Override
public void stop(Runnable runnable) {
stop();
runnable.run();
}
}
Here is schema.sql
CREATE TABLE IF NOT EXISTS t001i001(pf_id INTEGER,df_name VARCHAR(20));
--SET TABLE t001i001 SOURCE 't001i001.csv;fs=|;vs=.';
Here is data.sql
insert into t001i001(pf_id, df_name) values(1, 'Shefat Hossain');
Where I want to add some script to perform some SET operation dynamically as like as what was commented in schema.sql on second line. using spring.
Any way to perform SET operation logically/dynamically inside Spring Application Context?
Here is wrong assumption of me as As I declared the property at applicationContext.xml on hsqldb bean as below:
<prop key="hsqldb.default_table_type">text</prop>
It's suppose to me that it would be help us to defaulting database table engine TEXT instead of MEMORY. As the table default engine was MEMORY so the 2nd line of schema.sql not executing. after editing schema.sql it working fine, no problem on SET operation as following:
CREATE TEXT TABLE IF NOT EXISTS t001i001(pf_id INTEGER,df_name VARCHAR(20));
SET TABLE t001i001 SOURCE 't001i001.csv;fs=|;vs=.';

Spring Hibernate JPA HSQL Table not found in statement

I'm training Spring persistence with LocalContainerEntityManagerFactoryBean and getting error:
Caused by: java.sql.SQLException: Table not found in statement [insert into PERSON (ID, email, name) values (null, ?, ?)]
Don't really know what I did wrong
My Main class (for test only)
package com.me.test;
import com.me.model.Person;
import com.me.service.PersonService;
import java.util.List;
import java.util.logging.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
/**
*
*/
public static final Logger log = Logger.getLogger(Main.class.getName());
public static void main(String[] args) {
log.info("************** BEGINNING PROGRAM **************");
ApplicationContext context = new ClassPathXmlApplicationContext("WEB-INF/spring-config.xml");
PersonService personService = (PersonService) context.getBean("personService");
Person person = new Person();
person.setName("name");
person.setEmail("name#name.com");
personService.addPerson(person);
log.info("Person : " + person + " added successfully");
List<Person> persons = personService.fetchAllPersons();
log.info("The list of all persons = " + persons);
log.info("************** ENDING PROGRAM *****************");
}
}
My 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:aop="http://www.springframework.org/schema/aop"
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/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.me" />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml" />
<property name="persistenceUnitName" value="personPersistenceUnit" />
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<property name="jpaDialect" ref="jpaDialect" />
</bean>
<bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="HSQL" />
<property name="databasePlatform" value="org.hibernate.dialect.HSQLDialect" />
</bean>
<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<property name="dataSource" ref="dataSource" />
<property name="jpaDialect" ref="jpaDialect" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.hsqldb.jdbcDriver" />
<property name="url" value="jdbc:hsqldb:file:/home/me/Pulpit/hsql1/db3; shutdown=true" />
<property name="username" value="sa" />
<property name="password" value="" />
</bean>
<bean id="dbUtil" class="com.me.service.DbUtil">
<!-- init-method="initialize">-->
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
version="1.0">
<persistence-unit name="personPersistenceUnit" transaction-type="RESOURCE_LOCAL" >
<class>com.me.model.Person</class>
</persistence-unit>
</persistence>
PersonService class
package com.me.service;
import com.me.dao.PersonDao;
import com.me.model.Person;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
#Component
public class PersonService {
private PersonDao personDao;
public PersonDao getPersonDao() {
return personDao;
}
#Autowired
public void setPersonDao(PersonDao personDao) {
this.personDao = personDao;
}
public void addPerson(Person person) {
getPersonDao().insert(person);
}
public List<Person> fetchAllPersons() {
return getPersonDao().selectAll();
}
}
personDAO class
package com.me.dao;
import com.me.model.Person;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
#Repository("personDao")
#Transactional(propagation = Propagation.REQUIRED)
public class PersonDao {
private static final String SELECT_QUERY = "select p from Person p";
#PersistenceContext
private EntityManager entityManager;
public EntityManager getEntityManager() {
return entityManager;
}
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
public void insert(Person person) {
entityManager.persist(person);
}
public List<Person> selectAll() {
Query query = entityManager.createQuery(SELECT_QUERY);
List<Person> persons = (List<Person>) query.getResultList();
return persons;
}
}
What's wrong here guys?
edit:
adding person class:
package com.me.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "PERSON")
public class Person implements Serializable{
private Integer id;
private String name;
private String email;
#Id
#GeneratedValue
#Column(name = "ID")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", email=" + email + "]";
}
}
and persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
version="1.0">
<persistence-unit name="personPersistenceUnit" transaction-type="RESOURCE_LOCAL" >
<class>com.me.model.Person</class>
</persistence-unit>
</persistence>
The problem is that you have not told Hibernate anywhere that it needs to create the tables when it loads.
An easy way to do that would be to add
<properties>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
</properties>
inside persistence.xml after <class>

sessionFactory is null when accessing DAO

I am trying to integrate Spring+Hibernate4, but when I access my DAOs I get a nullPointerException on the sessionFactory object.
This is my AbstractDao:
#Repository
public class AbstractDaoHibernateImpl {
private SessionFactory sessionFactory;
public AbstractDaoHibernateImpl() {
}
#Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
protected Session getSession() {
return getSessionFactory().getCurrentSession();
}
protected Order getOrder(String orderBy, boolean isOrderAsc) {
if (isOrderAsc)
return Order.asc(orderBy);
else
return Order.desc(orderBy);
}
}
This is my entity bean config:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!-- transacciones -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="SessionFactory"/>
</bean>
<!--Beans de los servicios de la aplicacion -->
<bean id="userService" class="com.app.service.user.UserServiceImpl"/>
<bean name="userDAO" class="com.app.model.user.dao.UserDaoImpl">
<property name="sessionFactory" ref="SessionFactory" />
</bean>
<bean id="SessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
</beans>
And this is the rest of my appContext
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jee="http://www.springframework.org/schema/jee"
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
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">
<context:component-scan base-package="com.app.controllers" />
<mvc:annotation-driven />
<context:annotation-config />
<tx:annotation-driven transaction-manager="transactionManager"/>
<import resource="applicationDatasource.xml" />
<import resource="applicationEntityBean.xml" />
</beans>
And finally this is my Service object:
#Service
public class UsuarioServiceImpl implements IUsuarioService {
#Autowired
private IUserDao userDao;
public List<User> getUsers() throws GenericDataBaseException {
return userDao.findAll();
}
}
Shouldn't the sessionFactory object be injected like this?
This is the whole stack trace:
java.lang.NullPointerException
at es.plexus.core.dao.impl.GenericDaoHibernateImpl.findAll(GenericDaoHibernateImpl.java:243)
at es.plexus.service.usuario.UsuarioServiceImpl.getUsuarios(UsuarioServiceImpl.java:20)
at es.plexus.controller.usuario.UsuarioController.listUsuarios(UsuarioController.java:24)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:213)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:722)
EDIT: userDao:
public class UserDaoImpl extends GenericDaoHibernateImpl<Usuario, Long> implements IUserDao {
}
which extends GenericDao:
public class GenericDaoHibernateImpl<E, PK extends Serializable> extends AbstractDaoHibernateImpl implements GenericDao<E, PK> {
private Class<E> entityClass;
public GenericDaoHibernateImpl() {
this.entityClass = (Class<E>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
public List<E> findAll() throws GenericDataBaseException {
try {
Criteria criteria = getSession().createCriteria(getEntityClass());
List<E> result = criteria.list();
/*
* if (result == null || result.size() == 0) throw new
* NoSearchResultException("", getEntityClass().getName());
*/
return result;
} catch (Throwable t) {
Collection<Object> args = new ArrayList<Object>();
throw exceptionHandler.handle(this, t, "findAll", args);
}
}
(...)
}
I see no transactions defined anywhere in your code.
In this case I recommend you put them on your service method :
#Transactional(readOnly = true)
public List<User> getUsers() throws GenericDataBaseException {
return userDao.findAll();
}
But you seem to be developing a rather complex class hierarchy, all you need is one generic repository and then instantiate that for different types. You don't have to use a service class, they are only recommended when using multiple aggregate roots/complex logic - not a simple getter.
Let me take a guess.
Is your DAO under the package com.app.controllers? If not add your dao package to the component scan as in <context:component-scan base-package="com.app.controllers, com.app.model.user.dao" />

How to get spring configuration from database

I'm using Eclipse Juno, JDK 7, tomcat 7.0.29, hibernate 4.1.5 and Spring 3.1.2.
I'm trying to load Spring configuration info from database. This is what I could do until now:
WEB.XML
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/context-beans.xml
</param-value>
</context-param>
jdbc.properties
jdbc.driver_class=com.microsoft.sqlserver.jdbc.SQLServerDriver
jdbc.url=jdbc:sqlserver://localhost;databaseName=mydbname;
jdbc.username=<my_usr>
jdbc.password=<my_pwd>
context-beans.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:oxm="http://www.springframework.org/schema/oxm"
xmlns:security="http://www.springframework.org/schema/security"
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-3.1.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
http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.1.xsd">
<!-- Configure which package will contain our components -->
<context:component-scan base-package="com.xxx" />
<context:annotation-config />
<mvc:annotation-driven />
<mvc:resources mapping="/static/**" location="/static/" />
<tx:annotation-driven />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="appPersistenceUnit" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="dataSource" class="org.apache.tomcat.dbcp.dbcp.BasicDataSource" p:driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
p:url="jdbc:sqlserver://localhost;databaseName=appDB" p:username="theUserName" p:password="thePassword" destroy-method="close"/>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" lazy-init="false" >
<property name="dataSource" ref="dataSource" />
<property name="lazyInit" value="false" />
</bean>
<bean id="appProperties" class="com.xxx.web.util.MyAppPropertyPlaceholderConfigurer">
<property name="nameColumn" value="key" />
<property name="valueColumn" value="value" />
<property name="tableName" value="app_params" />
<property name="whereClause" value="param_type = 'GLOBAL'" />
<property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>
<!-- Files path configuration -->
<mvc:resources mapping="/iconfiles/**" location="file:/${PATH.ICON_FILES}" />
</beans>
Please consider table app_params contains 1 record where key="PATH.ICON_FILES", value="c:/temp/icons/" and param_type="GLOBAL".
MyAppPropertyPlaceholderConfigurer
package com.xxx.web.util;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
public class MyAppPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
private JdbcTemplate jdbcTemplate;
private String nameColumn;
private String valueColumn;
private String tableName;
private String whereClause;
public MyAppPropertyPlaceholderConfigurer() {
super();
setPlaceholderPrefix("${");
}
#Override
protected void loadProperties(final Properties props) throws IOException {
if (null == props) {
throw new IOException("No properties passed by Spring framework - cannot proceed.");
}
String sql = String.format("SELECT [%s], [%s] FROM [%s] %s", nameColumn, valueColumn, tableName, whereClause);
logger.info("Reading configuration properties from database. Query=" + sql);
try {
jdbcTemplate.query(sql, new RowCallbackHandler() {
#Override
public void processRow(ResultSet rs) throws SQLException {
String name = rs.getString(nameColumn);
String value = rs.getString(valueColumn);
if (null == name || null == value) {
throw new SQLException("Configuration database contains empty data. Name='" + (name == null ? "" : name)
+ "', Value='" + (value == null ? "" : value) + "'.");
}
props.setProperty(name, value);
}
});
} catch (Exception e) {
logger.fatal("There is an error in either 'application.properties' or the configuration database.");
throw new IOException(e);
}
if (props.size() == 0) {
logger.fatal("The configuration database could not be reached or does not contain any properties in '" + tableName
+ "'.");
} else {
logger.info("Application config info loaded from configuration database.");
}
}
#Override
protected String convertPropertyValue(String originalValue) {
if (originalValue.startsWith("!!")) {
// TODO ex: return EncryptUtil.decrypt(originalValue); see org.owasp.esapi.reference.crypto.EncryptedPropertiesUtils
return originalValue;
}
return originalValue;
}
public void setJdbcTemplate(JdbcTemplate newJdbcTemplate) {
this.jdbcTemplate = newJdbcTemplate;
}
public void setNameColumn(String newNameColumn) {
this.nameColumn = newNameColumn;
}
public void setValueColumn(String newValueColumn) {
this.valueColumn = newValueColumn;
}
public void setTableName(String newTableName) {
this.tableName = newTableName;
}
public void setWhereClause(String newWhereClause) {
if (newWhereClause == null || newWhereClause.trim().length() == 0) {
this.whereClause = "";
} else {
if (newWhereClause.trim().toUpperCase().startsWith("WHERE ")) {
this.whereClause = newWhereClause;
} else {
this.whereClause = "WHERE " + newWhereClause;
}
}
}
}
Doing it this way works as expected and I have variable ${PATH.ICON_FILES} properly resolved.
However, I don't want to have my dataSource bean with username, password and all stuff hard coded on the XML file. I would like to load it from another property file, preferentially encrypted.
How do I get this done?
I already tried to add another PropertyPlaceholderConfigurer with jdbc configuration (plain text at this time) by adding the code below into context-beans.xml:
<bean id="jdbcConfigurer" name="jdbcConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
Then I changed dataSource bean to read from there:
<bean id="dataSource" name="dataSource" class="org.apache.tomcat.dbcp.dbcp.BasicDataSource" p:driverClassName="${jdbc.driver_class}"
p:url="${jdbc.url}" p:username="${jdbc.username}" p:password="${jdbc.password}" destroy-method="close" />
When I try to run I get the following error:
[2012-10-10 11:33:48,744] WARN (SQLErrorCodesFactory.java:227) - Error while extracting database product name - falling back to empty error codes
org.springframework.jdbc.support.MetaDataAccessException: Could not get Connection for extracting meta data; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot load JDBC driver class '${jdbc.driver_class}'
Any idea what I'm doing wrong here? Looks like it is instantiating MyAppPropertyPlaceholderConfigurer prior to getting the values from the regular PropertyPlaceholderConfigurer...
Thanks.

Resources