I'am facing an error with #Autowired annotation.
UserService class contain JdbcTemplate attribute with getter/setter.
Every thing works fine if I "wire" that attribute from within context file:
<bean id="userService" class="org.tuto.service.UserServiceImpl">
<property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>
but with Autowired i get this-after error message.
Can someone tell me how to inject by #Autowired with no need to configure it. Thanks in Advance.
org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.jdbc.core.JdbcTemplate org.tuto.service.UserServiceImpl.jdbcTemplate; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.jdbc.core.JdbcTemplate] 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)}
UserServiceImpl.java:
package org.tuto.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.tuto.mapper.UserMapper;
import org.tuto.model.User;
#Service("userService")
#Transactional
public class UserServiceImpl implements UserService{
#Autowired
private JdbcTemplate jdbcTemplate;
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
#Override
public List<User> findAllUsers() {
String SQL = "select * from user";
UserMapper userMapper = new UserMapper();
List<User> result = jdbcTemplate.query(SQL, userMapper);
return result;
}
#Override
public User findById(long id) {
String SQL = "select * from users where id = ?";
User result = jdbcTemplate.queryForObject(SQL, new Object[] { id }, new UserMapper());
return result;
}
}
spring-servlet.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<context:annotation-config />
<context:component-scan base-package="org.tuto" />
<!-- bean definitions go here -->
<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/****" />
<property name="username" value="****" />
<property name="password" value="****" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<constructor-arg ref="dataSource" />
</bean>
<bean id="userService" class="org.tuto.service.UserServiceImpl">
<property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>
</beans>
Related
I'm developing multiple-jobs-in-quartz-spring-example which is combination of Spring + Quartz + Spring Data JPA. I'm looking to developed a code which will run in 5 sec, it will hit to DB and fetches a records from DB.
I am close to making it working but I see small problem. In my JobA.class, why don't I get an instance of CustomerRepository.java? It's always null and thats why code unable to hit to DB.
Source code at: http://www.github.com/test512/multiple-jobs-in-quartz-spring-example.git.
JobA.java
#Service
public class JobA extends QuartzJobBean {
private CustomerRepository customerRepository = null;
#Autowired
public JobA(CustomerRepository customerRepository) {
this.customerRepository = customerRepository;
}
public JobA() { }
#Override
protected void executeInternal(JobExecutionContext executionContext) throws JobExecutionException {
System.out.println("~~~~~~~ Job A is runing ~~~~~~~~");
Trigger trigger = executionContext.getTrigger();
System.out.println(trigger.getPreviousFireTime());
System.out.println(trigger.getNextFireTime());
getCustomerList();
}
private List<Customer> getCustomerList(){
List<Customer> customers = customerRepository.findAll();
for (Customer customer : customers) {
System.out.println("------------------------------");
System.out.println("ID : "+customer.getId());
System.out.println("NAME : "+customer.getName());
System.out.println("STATUS : "+customer.getStatus());
}
return customers;
}
}
Customer.java
#Entity
#Table(name="customer")
public class Customer {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="ID")
private Long id;
#Column(name="NAME")
private String name;
#Column(name="STATUS")
private String status;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
CustomerRepository.java
public interface CustomerRepository extends JpaRepository<Customer, Long>{
}
dataSourceContext.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:jdbc="http://www.springframework.org/schema/jdbc"
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/context http://www.springframework.org/schema/context/spring-context.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">
<context:property-placeholder location="classpath:database.properties"/>
<!-- <jdbc:initialize-database data-source="dataSource" enabled="true">
<jdbc:script location="classpath:db-schema.sql" />
<jdbc:script location="classpath:db-test-data.sql" />
</jdbc:initialize-database> -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${mysql.driver.class.name}" />
<property name="url" value="${mysql.url}" />
<property name="username" value="${mysql.username}" />
<property name="password" value="${mysql.username}" />
</bean>
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="generateDdl" value="true"/>
<property name="database" value="MYSQL"/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
<!-- spring based scanning for entity classes-->
<property name="packagesToScan" value="com.mkyong.*"/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"/>
</beans>
Spring-Quartz.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:repository="http://www.springframework.org/schema/data/repository"
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/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/data/repository http://www.springframework.org/schema/data/repository/spring-repository.xsd">
<import resource="classpath:dataSourceContext.xml"/>
<jpa:repositories base-package="com.mkyong.repository" />
<context:component-scan base-package="com.mkyong.*" />
<context:annotation-config />
<bean id="jobA" class="com.mkyong.job.JobA" />
<bean id="jobB" class="com.mkyong.job.JobB" />
<bean id="jobC" class="com.mkyong.job.JobC" />
<bean id="autowiredA" class="com.mkyong.job.JobASpringBeanJobFactory" />
<!-- ~~~~~~~~~ Quartz Job ~~~~~~~~~~ -->
<bean name="JobA" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobClass" value="com.mkyong.job.JobA" />
</bean>
<bean name="JobB" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobClass" value="com.mkyong.job.JobB" />
</bean>
<bean name="JobC" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobClass" value="com.mkyong.job.JobC" />
</bean>
<!-- ~~~~~~~~~~~ Cron Trigger, run every 5 seconds ~~~~~~~~~~~~~ -->
<bean id="cronTriggerJobA" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="JobA" />
<property name="cronExpression" value="0/5 * * * * ?" />
</bean>
<bean id="cronTriggerJobB" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="JobB" />
<property name="cronExpression" value="0/5 * * * * ?" />
</bean>
<bean id="cronTriggerJobC" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="JobC" />
<property name="cronExpression" value="0/5 * * * * ?" />
</bean>
<!-- ~~~~~~~~~~~~~~~~ Scheduler bean Factory ~~~~~~~~~~~~~~~~ -->
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="jobFactory" ref="autowiredA"/>
<property name="triggers">
<list>
<ref bean="cronTriggerJobA" />
<!-- <ref bean="cronTriggerJobB" />
<ref bean="cronTriggerJobC" /> -->
</list>
</property>
</bean>
</beans>
JobASpringBeanJobFactory.java
public class JobASpringBeanJobFactory extends SpringBeanJobFactory implements ApplicationContextAware {
private transient AutowireCapableBeanFactory beanFactory;
#Override
public void setApplicationContext(final ApplicationContext context) {
beanFactory = context.getAutowireCapableBeanFactory();
}
#Override
protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
final Object job = super.createJobInstance(bundle);
beanFactory.autowireBean(job);
return job;
}
}
App.java
public class App {
public static void main(String[] args) throws Exception {
ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Quartz.xml");
}
}
Going through the following link http://codrspace.com/Khovansa/spring-quartz-with-a-database/ should help.
Quoting from the above link,
Quartz creates a new job instance on each invocation. It means that Quartz jobs are not regular Spring beans and we can't expect the Spring magic to take an effect automatically (and Spring's 'JobDetailFactoryBean' is not smart enough to do it for us). So we'll have to implement our own job factory that would overwrite the default SpringBeanJobFactory.
So you need to have a custom SpringBeanJobFactory by extending SpringBeanJobFactory & implementing ApplicationContextAware and finally invoke beanFactory.autowireBean(job)
I get error nullpointerexception in sessionFactory.getCurrentSession();
Spring Framework 4.0
Glassfish 4.1
hibernate 4.3.6.Final
When I call Session session = sessionFactory.getCurrentSession(); i get error in glassfish server log, but setSessionFactory is set by Spring. What is wrong in my code. Please Help! :)
It's Spring #Component
package service;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ApplicationScoped;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Repository;
import model.Payments;
#Component
#ManagedBean(name = "paymentsService")
#ApplicationScoped
#Repository
public class PaymentsService {
private SessionFactory sessionFactory ;
public PaymentsService()
{
}
public PaymentsService(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
#Autowired
public void setSessionFactory( SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
// #Transactional
public void register(){
Session session = sessionFactory.getCurrentSession();
}
}
It's primefaces #ManagedBean
package backbean;
import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.context.FacesContext;
import javax.faces.bean.SessionScoped;
import model.Payments;
import service.PaymentsService;
#ManagedBean
#ApplicationScoped
public class Paymentsbeen implements Serializable {
/**
*
*/
private static final long serialVersionUID = 7719279452314113041L;
public String register() {
paymentsService.register();
}
}
It's Spring config file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/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-4.0.xsd">
<!-- Enable Spring Annotation Configuration -->
<context:annotation-config />
<!-- Scan for all of Spring components such as Spring Service -->
<context:component-scan base-package="service.PaymentsService"></context:component-scan>
<!-- Create Data Source bean -->
<!--<bean id="dbDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:jdbc/__TestPool"/>
</bean>-->
<bean id="DataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost:5432/ihomefinance" />
<property name="username" value="postgres" />
<property name="password" value="1" />
</bean>
<!-- Define SessionFactory bean -->
<bean id="hibernate3AnnotatedSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="DataSource" />
<property name="annotatedClasses">
<list>
<value>model.Payments</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.show_sql">false</prop>
</props>
</property>
</bean>
<!-- Transaction Manager
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="hibernate3AnnotatedSessionFactory" />
</bean>-->
<bean id="PaymentsServiceID" class="service.PaymentsService">
<property name="sessionFactory" ref="hibernate3AnnotatedSessionFactory" />
</bean>
<!-- Detect #Transactional Annotation
<tx:annotation-driven transaction-manager="transactionManager" />-->
</beans>
I am trying develope a small application using Spring Framework with Annotation but i really not able to recognized what i made mistake that InternalResourceViewResolver class not handling request that is coming from .jsp page. here is my project details.
index.jsp
<jsp:forward page="login.form" ></jsp:forward>
spring-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="com.nody.spring.controller"></context:component-scan>
<context:annotation-config></context:annotation-config>
<!-- Handler Mapping -->
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMappping"></bean>
<!-- View Resolver -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
<property name="url" value="jdbc:oracle:thin:#localhost:1521:xe"></property>
<property name="username" value="scott"></property>
<property name="password" value="tiger"></property>
</bean>
</beans>
LoginController.java
package com.nody.spring.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class LoginController {
private LoginService loginService;
#Autowired
public void setLoginService(LoginService loginService) {
this.loginService = loginService;
}
#RequestMapping(value="/login.form", method=RequestMethod.GET)
public ModelAndView getLoginPage()
{
return new ModelAndView("login");
}
#RequestMapping(value="check", method=RequestMethod.POST)
public ModelAndView checkLogin(#RequestParam("uname")String s1,#RequestParam("pword")String s2)
{
boolean b=loginService.check(s1,s2);
if(b)
return new ModelAndView("success");
else
return new ModelAndView("failure");
}
}
LoginService.java
package com.nody.spring.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
#Repository
public class LoginService {
private JdbcTemplate jt;
#Autowired
#Qualifier("jt")
public void setJt(JdbcTemplate jt)
{
this.jt=jt;
}
public boolean check(String s1,String s2)
{
#SuppressWarnings("deprecation")
int i=jt.queryForInt("select count(*) from users where uname=? and pword=?",s1,s2);
if(i==1)
return true;
else
return false;
}
}
List of jars
aspectj-weaver.jar
atomikos-transactions-api.jar
atomikos-transactions-jta.jar
atomikos-util.jar
commons-logging-api-1.1.1.jar
javax.transaction-3.1.jar
jta.jar
mysql-connector-java-5.1.6.jar
ojdbc14.jar
spring-aop-4.1.4.RELEASE.jar
spring-beans-4.1.4.RELEASE.jar
spring-context-4.1.4.RELEASE.jar
spring-context-support-4.1.4.RELEASE.jar
spring-core-4.1.4.RELEASE.jar
spring-expression-4.1.4.RELEASE.jar
spring-jdbc-4.1.4.RELEASE.jar
spring-tx-4.1.4.RELEASE.jar
transactions-3.7.0.jar
transactions-jdbc-3.7.0.jar
aopalliance.jar
aspectjrt-1.8.5.jar
failure.jsp
<form action="check.form" method="POST">
Username:<input type=text name="uname"><br>
Password<input type=password name="pword"><br>
<input type=submit value="SUBMIT">
</form>
success.jsp
<h1>Login Success !!!</h1>
failure.jsp
<h1>Login Success !!!</h1>
and Oracle Table name is 'users' with 2 columns 'uname' and 'pword'
I don't know, if I understand correctly, but you have an error with loading .jsp pages?
<!-- View Resolver -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
Looks like you saying to spring, to look for .jsp pages in direct directory (webapp probably). Where do you keep your .jsp files? You should provide exact folder which containts .jsp files, like <beans:property name="prefix" value="/WEB-INF/views/" />
Hello I´m newbie in spring mvc, i´m using #autowired but i don´t know the solution. Thx you. Sorry but my english, i´m learning it.
I have two class Empresa.java and Ldiario.java. Empresa.java it works.
UPDATE
I updated the following code but I have the same error.
app-config.xml
<!-- Hibernate Session Factory -->
<bean id="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="packagesToScan" value="com.atorresbr.springapp.**"/>
and I added a bean.
<bean id="diarioBean" class="com.atorresbr.springapp.bean.DiarioBean"/>
Error
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'diarioBean': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.atorresbr.springapp.model.Ldiario com.atorresbr.springapp.bean.DiarioBean.ldiario; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.atorresbr.springapp.model.Ldiario] 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)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:288)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1116)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
DiarioBean.java
#ManagedBean(name="diarioBean")
#SessionScoped
#Component
public class DiarioBean {
#Autowired
private Ldiario ldiario;
#Autowired
private Ldiario selectedLdiario;
public DiarioBean(){
}
public Ldiario getLdiario() {
return ldiario;
}
public void setLdiario(Ldiario ldiario) {
this.ldiario = ldiario;
}
public Ldiario getSelectedLdiario() {
return selectedLdiario;
}
public void setSelectedLdiario(Ldiario selectedLdiario) {
this.selectedLdiario = selectedLdiario;
}
}
Ldiario.java
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import java.io.Serializable;
import java.sql.Blob;
import java.util.Date;
#Entity
#Table(name = "LDIARIO2014")
public class Ldiario implements Serializable{
#Id
#Column(name = "CLAVE")
#GeneratedValue private Integer CLAVE;
#ManyToOne
#JoinColumn (name = "empresa")
private Empresa empresa;
#Column(name = "ASIENTO")
private Integer ASIENTO;
#Column(name = "ORDEN")
private Integer ORDEN;
#Column(name = "FECHA")
private Date FECHA;
app-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<!-- Scans the classpath of this application for #Components #Service #Repository to deploy as
beans -->
<context:component-scan base-package="com.atorresbr.springapp" />
<!-- Configures the #Controller programming model -->
<mvc:annotation-driven />
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="diarioBean" class="com.atorresbr.springapp.bean.DiarioBean"/>
<!-- JDBC Data Source. It is assumed you have MySQL running on localhost port 3306 with
username root and blank password. Change below if it's not the case -->
<bean id="myDataSource"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}"
p:username="${jdbc.username}"
p:password="${jdbc.password}"
p:validationQuery="${jdbc.validationQuery}" />
<!--
<bean id="myDataSource" 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/pizzashop"/>
<property name="username" value="root"/>
<property name="password" value=""/>
<property name="validationQuery" value="SELECT 1"/>
</bean> -->
<!-- Hibernate Session Factory -->
<bean id="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="packagesToScan" value="com.atorresbr.springapp.**"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- Hibernate Transaction Manager -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
<!-- Activates annotation based transaction management -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
I'm trying to make a project using Spring MVC and JPA but I have a problem when I'm trying to launch the app - there's an exception that looks like this (few lines of each):
exception
javax.servlet.ServletException: Servlet.init() for servlet appServlet threw exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
root cause
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'homeController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.lovemyway.itlovers.persistence.JpaUserDao com.lovemyway.itlovers.controllers.HomeController.jpaUserDao; nested exception is java.lang.IllegalArgumentException: Can not set com.lovemyway.itlovers.persistence.JpaUserDao field com.lovemyway.itlovers.controllers.HomeController.jpaUserDao to $Proxy33
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
My code looks like this:
JpaUserDao.java
package com.lovemyway.itlovers.persistence;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.lovemyway.itlovers.domain.User;
#Repository("jpaUserDao")
#Transactional
public class JpaUserDao implements UserDao {
#PersistenceContext
private EntityManager em;
public void addUser(User user) {
em.persist(user);
}
public void removeUser(User user) {
em.remove(user);
}
public User findUserById(int id) {
return em.find(User.class, id);
}
}
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<mvc:annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<mvc:resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.lovemyway.itlovers" />
<tx:annotation-driven transaction-manager="transactionManager" />
<beans:bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<property name="persistenceUnitName" value="ITlovers"/>
</beans:bean>
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/itlovers" />
<property name="username" value="root" />
<property name="password" value="root" />
<property name="initialSize" value="5" />
<property name="maxActive" value="10" />
</beans:bean>
<beans:bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="MYSQL" />
<property name="showSql" value="true"/>
<property name="generateDdl" value="false"/>
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
</beans:bean>
<beans:bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</beans:bean>
<beans:bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<beans:bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
</beans>
And the controller causing exception:
HomeController.java
package com.lovemyway.itlovers.controllers;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.lovemyway.itlovers.domain.Rank;
import com.lovemyway.itlovers.domain.User;
import com.lovemyway.itlovers.persistence.JpaUserDao;
/**
* Handles requests for the application home page.
*/
#Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
#Autowired
private JpaUserDao jpaUserDao;
/**
* Simply selects the home view to render by returning its name.
*/
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! the client locale is "+ locale.toString());
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
Rank r = new Rank();
r.setColor("aa");
r.setDescription("a4aa");
r.setName("ranga");
User u = new User();
u.setActive(true);
u.setAdmin(true);
u.setUsername("szaku2");
u.setEmail("aaa");
u.setPassword("aaa");
u.setRegistrationDate(date);
u.setLastLoginDate(date);
u.setRank(r);
jpaUserDao.addUser(u);
jpaUserDao.findUserById(2);
model.addAttribute("serverTime", formattedDate);
return "home";
}
}
What am I doing wrong? I'm confused by too many xml files.. If I instantiate jpaUserDao using the new Constructor (I guess I annotated it by #Repository to not do so) i got NullPointerException.
Regards,
Marcin
You should declare your fields using interfaces, not implementation classes:
#Autowired
private UserDao userDao;
In addition to the fact that it's a good design practice, in your case not doing so doesn't allow Spring to inject interface-based proxy into that field.
Interface-based proxy for JpaUserDao is created in order to provide behaviours required by #Repository and #Transactional.
You are missing a setter for your jpaUserDao.
Add the following to your HomeController:
public setJpaUserDao(JpaUserDao jpaUserDao){
this.jpaUserDao = jpaUserDao;
}