i am not sure what i am doing wrong , i am trying to execute a stored-procedure using jdbc call but when ever i execute its hitting exception
java.lang.IllegalArgumentException: Property 'dataSource' is required .
Controller Class:
#Controller
public class GpsController {
#RequestMapping(value="h",method=RequestMethod.POST)
public void show(#ModelAttribute("PredefinedPath") PredefinedPath predefinedPath)
{
PredefinedPathService service=new PredefinedPathService();
//passing dto obj to service
boolean res= service.savePredefinedPath(predefinedPath);
}
DTO CLASS:
//Entity Class Getters and setters
public class PredefinedPath {
public int getPredefinedPath_Id() {
return PredefinedPath_Id;
}
public void setPredefinedPath_Id(int predefinedPath_Id) {
PredefinedPath_Id = predefinedPath_Id;
}
public String getPredefinedPath_Name() {
return PredefinedPath_Name;
}
public void setPredefinedPath_Name(String predefinedPath_Name) {
PredefinedPath_Name = predefinedPath_Name;
}
public String getSource() {
return Source;
}
public void setSource(String source) {
Source = source;
}
public String getDestination() {
return Destination;
}
public void setDestination(String destination) {
Destination = destination;
}
public String getEstimate_km() {
return Estimate_km;
}
public void setEstimate_km(String estimate_km) {
Estimate_km = estimate_km;
}
public double getSource_Latitude() {
return Source_Latitude;
}
public void setSource_Latitude(double source_Latitude) {
Source_Latitude = source_Latitude;
}
public double getSource_Longtitude() {
return Source_Longtitude;
}
public void setSource_Longtitude(double source_Longtitude) {
Source_Longtitude = source_Longtitude;
}
public double getDestination_Latitude() {
return Destination_Latitude;
}
public void setDestination_Latitude(double destination_Latitude) {
Destination_Latitude = destination_Latitude;
}
public double getDestination_Longtitude() {
return Destination_Longtitude;
}
public void setDestination_Longtitude(double destination_Longtitude) {
Destination_Longtitude = destination_Longtitude;
}
public String getEffectiveFromDate() {
return EffectiveFromDate;
}
public void setEffectiveFromDate(String effectiveFromDate) {
EffectiveFromDate = effectiveFromDate;
}
public String getEffectiveToDate() {
return EffectiveToDate;
}
public void setEffectiveToDate(String effectiveToDate) {
EffectiveToDate = effectiveToDate;
}
public int getStatus_Id() {
return Status_Id;
}
public void setStatus_Id(int status_Id) {
Status_Id = status_Id;
}
private int PredefinedPath_Id;
private String PredefinedPath_Name;
private String Source;
private String Destination;
private String Estimate_km;
private double Source_Latitude;
private double Source_Longtitude;
private double Destination_Latitude;
private double Destination_Longtitude;
private String EffectiveFromDate;
private String EffectiveToDate;
private int Status_Id;
}
DAO CLASS :
import javax.sql.DataSource;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
import com.Ss.App.dto.PredefinedPath;
public class PredefinedPathDaoImpl {
private DataSource dataSource;
private SimpleJdbcCall jdbcCall;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public boolean savePredefined(PredefinedPath predefinedPathDto)
{
System.out.println("INSIDE DAO");
this.jdbcCall = new SimpleJdbcCall(dataSource).withProcedureName("PredefinedPath_Insert");
SqlParameterSource sqlParameterSource = new MapSqlParameterSource()
.addValue("PredefinedPath_Name", predefinedPathDto.getPredefinedPath_Name())
.addValue("Source", predefinedPathDto.getSource())
.addValue("Destination", predefinedPathDto.getDestination())
.addValue("Source_Latitude", predefinedPathDto.getSource_Latitude())
.addValue("Source_Longtitude", predefinedPathDto.getSource_Longtitude())
.addValue("Destination_Latitude", predefinedPathDto.getDestination_Latitude())
.addValue("Destination_Longtitude", predefinedPathDto.getDestination_Longtitude())
.addValue("EffectiveFromDate",null)
.addValue("EffectiveToDate",null)
.addValue("Status_Id", 4);
jdbcCall.execute(sqlParameterSource);
return true;
}
}
Service Class:
import com.Ss.App.dto.PredefinedPath;
import com.Ss.App.model.dao.PredefinedPathDaoImpl;
public class PredefinedPathService {
PredefinedPathDaoImpl predefinedPathDao=new PredefinedPathDaoImpl();
public boolean savePredefinedPath(PredefinedPath predefinedPathdto)
{
boolean result=predefinedPathDao.savePredefined(predefinedPathdto);
return result;
}
}
Spring Config:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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">
<context:component-scan base-package="com.Ss.App"></context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/view/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- Definition for studentJDBCTemplate bean -->
<bean id="PredefinedPathDaoImpl" class="com.Ss.App.model.dao.PredefinedPathDaoImpl">
<property name="DataSource" ref="dataSource" />
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"></property>
<property name="url" value="jdbc:sqlserver://localhost:1433;DatabaseName=test"></property>
<property name="username" value="sa"></property>
<property name="password" value="pass"></property>
</bean>
<mvc:annotation-driven />
</beans>
web.config
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<display-name>SpringAngularjs</display-name>
<welcome-file-list>
<welcome-file>page.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
The service in your controller is not managed by Spring as you instantiate it yourself.
That's why the datasource is not set in this bean.
Replace :
#Controller
public class GpsController {
#RequestMapping(value="h",method=RequestMethod.POST)
public void show(#ModelAttribute("PredefinedPath") PredefinedPath predefinedPath)
{
PredefinedPathService service=new PredefinedPathService();
//passing dto obj to service
boolean res = service.savePredefinedPath(predefinedPath);
}
}
By
#Controller
public class GpsController {
#Autowired
private PredefinedPathService service;
#RequestMapping(value="h",method=RequestMethod.POST)
public void show(#ModelAttribute("PredefinedPath") PredefinedPath predefinedPath)
{
//passing dto obj to service
boolean res = service.savePredefinedPath(predefinedPath);
}
}
Related
I developed the application using spring transactions and insert records in the table.
I'm explicitly throwing the exception in DAO class but spring is inserting the record into the table rather than roll back the transaction.
I have created the two applications as below . In Case 1 record is inserted into table even though exception is thrown . But In Case 2 no record is inserted and spring roll back the transaction successfully. Can you explain me the difference between these two applications.
Case 1:
Item.java
public class Item {
int itemNo;
String itemName;
String itemType;
String itemSize;
public int getItemNo() {
return itemNo;
}
public void setItemNo(int itemNo) {
this.itemNo = itemNo;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemType() {
return itemType;
}
public void setItemType(String itemType) {
this.itemType = itemType;
}
public String getItemSize() {
return itemSize;
}
public void setItemSize(String itemSize) {
this.itemSize = itemSize;
}
}
ItemDao
#Service
public class ItemDao {
#Autowired
JdbcTemplate jdbcTemplate ;
void insert(Item item){
jdbcTemplate.update("insert into item_test(itemno, itemtype,itemsize,itemname) values (?,?,?,?)", new Object[]{item.getItemNo(),item.getItemType(),item.getItemSize(),item.getItemName()});
int a=2/0;
}
}
ItemService.java
#Service
public class ItemService {
#Autowired
ItemDao itemDao;
#Transactional
public void insert(Item item){
try{
itemDao.insert(item);
}
catch(Exception e){
e.printStackTrace();
}
}
}
Test.java
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ct = new ClassPathXmlApplicationContext("spring.xml");
ItemService itemService = ct.getBean("itemService", ItemService.class);
Item item = new Item();
item.setItemNo(1234);
item.setItemName("sofa");
item.setItemSize("4");
item.setItemType("furniture");
itemService.insert(item);
}
}
spring.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: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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- Enable Annotation based Declarative Transaction Management -->
<tx:annotation-driven proxy-target-class="true" transaction-manager="transactionManager" />
<context:component-scan base-package="com.spring.springtransaction" />
<!-- Creating TransactionManager Bean, since JDBC we are creating of type
DataSourceTransactionManager -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- MySQL DB DataSource -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#locahost:1521:xe)))" />
<property name="username" value="system" />
<property name="password" value="system" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="itemService" class="com.spring.springtransaction.ItemService" />
</beans>
Case 2:
ItemService.java
#Service
public class ItemService {
#Autowired
ItemDao itemDao;
#Autowired
ItemManger itemManger;
#Transactional
public void insert(Item item){
try{
itemManger.insert(item);
}
catch(Exception e){
e.printStackTrace();
}
}
}
ItemManger.java
#Service
public class ItemManger {
#Autowired
ItemDao itemDao;
#Transactional
public void insert(Item item){
itemDao.insert(item);
}
}
ItemDao.java
#Service
public class ItemDao {
#Autowired
JdbcTemplate jdbcTemplate ;
void insert(Item item){
jdbcTemplate.update("insert into item_test(itemno, itemtype,itemsize,itemname) values (?,?,?,?)", new Object[]{item.getItemNo(),item.getItemType(),item.getItemSize(),item.getItemName()});
int a=2/0;
}
}
Annotate you ItemDao as #Repository instead of #Service
You should execute unit test with spring Transactional context instead of main , for example using TestNG:
#ContextConfiguration(classes = {ConfigurationClass.class})
#ActiveProfiles({"test"})
public class TestItemDAO extends AbstractTransactionalTestNGSpringContextTests {
#Autowired
private ItemDao dao;
#Test
public void testItemDao() {
dao.insert(item);
}
}
Remove the try block, you are trying to handle the exception so this is reason why RollbackException is not cutting the transaction stream.
I wrote below 2 Java classes for learning Spring, but getting FileNotFoundException after running the code. Please help me to resolve this issue.
Is it not taking the path of the XML file?
package com.javatpoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("xmlContext.xml");
//Resource resource=new ClassPathResource("xmlContext.xml");
//BeanFactory factory=new XmlBeanFactory(resource);
Student student = (Student)context.getBean("studentbean");
student.displayName();
}
}
2)
package com.javatpoint;
public class Student {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void displayName() {
System.out.println("Name :"+name);
}
}
XML 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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="studentbean" class="com.javatpoint.Student">
<property name="name" value="Vimal Jaiswal"></property>
</bean>
</beans>
I am getting the below error, I have gone through all of the similar issues, but don't able to figure out where I am going wrong.
Here is the error:
Exception in thread "main" javax.persistence.TransactionRequiredException: No transactional EntityManager available
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:275)
at com.sun.proxy.$Proxy19.persist(Unknown Source)
at com.project.vibhas.dao.hibernate.GenericDaoJpa.save(GenericDaoJpa.java:45)
at com.project.vibhas.service.impl.PersonServiceImpl.save(PersonServiceImpl.java:22)
at com.project.vibhas.domain.App.main(App.java:25)
Here are my code:
package com.project.vibhas.dao.hibernate;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.transaction.annotation.Transactional;
import com.project.vibhas.dao.GenericDao;
import com.project.vibhas.domain.DomainObject;
public class GenericDaoJpa<T extends DomainObject> implements GenericDao<T> {
private Class<T> type;
protected EntityManager entityManager;
#PersistenceContext
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
public GenericDaoJpa(Class<T> type) {
super();
this.type = type;
}
#Transactional
public void save(T object) {
System.out.println("inside generic dao");
entityManager.persist(object);
}
public void delete(T object) {
entityManager.remove(object);
}
}
My Dao class:
#Repository("personDao")
public class PersonDaoJpa extends GenericDaoJpa<Person> implements PersonDao {
public PersonDaoJpa() {
super(Person.class);
}
public Person authenticatePerson(String username, String password)
throws DataAccessException, AuthenticationException {
List<Person> results = null;
Query query = entityManager
.createQuery("from Person as p where p.username = :username and p.password = :password");
query.setParameter("username", username);
query.setParameter("password", password);
results = query.getResultList();
if (results == null || results.size() <= 0) {
throw new AuthenticationException("No users found");
} else {
return results.get(0);
}
}
public Person getPersonByUsername(String username)
throws DataAccessException, EntityNotFoundException {
List<Person> results = null;
Query query = entityManager
.createQuery("from Person as p where p.username = :username");
query.setParameter("username", username);
results = query.getResultList();
if (results == null || results.size() <= 0) {
throw new EntityNotFoundException(username + " not found");
} else {
return results.get(0);
}
}
}
My sercice Class:
package com.project.vibhas.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.project.vibhas.dao.PersonDao;
import com.project.vibhas.domain.Person;
import com.project.vibhas.service.PersonService;
#Service("personService")
public class PersonServiceImpl implements PersonService{
#Autowired
PersonDao personDao;
public void setPersonDao(PersonDao personDao) {
this.personDao = personDao;
}
public void save(Person person) {
System.out.println("Inside service");
//personDao.get(1L);
personDao.save(person);
}
}
My Test Class:
package com.project.vibhas.domain;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.project.vibhas.service.PersonService;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
ApplicationContext appContext = new ClassPathXmlApplicationContext(
"classpath*:META-INF/spring/spring-jpa.xml");
PersonService personService = (PersonService) appContext.getBean("personService");
Person person = new Person();
person.setId(1L);
personService.save(person);
System.out.println("Done");
}
}
Spring-Jpa.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- The rest of the config is covered below -->
<context:annotation-config />
<context:spring-configured />
<context:component-scan base-package="com.project" />
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close"
p:driverClassName="org.postgresql.Driver"
p:url="jdbc:postgresql://localhost:5433/mypostgresdb"
p:username="postgres"
p:password="root" />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource"/>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory" />
<tx:annotation-driven mode="aspectj"
transaction-manager="transactionManager" />
</beans>
Persistence.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="galleryPersistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
<!--
value='create' to build a new database on each run;
value='update' to modify an existing database;
value='create-drop' to create and drop tables on each run;
value='validate' makes no changes to the database
-->
<property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
This question already has answers here:
Why is my Spring #Autowired field null?
(21 answers)
Closed 7 years ago.
I'm trying to learn Spring MVC and Hibernate. When I try to run tests I have "Exception in thread "main" java.lang.NullPointerException".
public interface VacancyDAO
package pro.asfert.jobparser.dao;
public interface VacancyDAO {
void LoadDataBase(String query);
void FindVacancy(String queries);}
public class VacancyDAOImpl
package pro.asfert.jobparser.dao;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
#Repository
public class VacancyDAOImpl implements VacancyDAO {
#Autowired
private SessionFactory sessionFactory;
public void LoadDataBase(String query) {
sessionFactory.getCurrentSession().createQuery(query);
}
public void FindVacancy(String queries) {
if (queries.contains("По вашему запросу: ")) {
System.out.print(queries);
} else {
sessionFactory.getCurrentSession().createQuery(queries);
}
}
}
public interface VacancyService
package pro.asfert.jobparser.service;
public interface VacancyService {
void LoadDataBase();
void FindVacancy(String queries);
}
**public class VacancyServiceImpl**
package pro.asfert.jobparser.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pro.asfert.jobparser.dao.VacancyDAO;
import pro.asfert.jobparser.domain.Parser;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
#Service
public class VacancyServiceImpl implements VacancyService {
#Autowired
private VacancyDAO VacancyDAO;
public static void main(String[] args) {
VacancyServiceImpl vacancyService = new VacancyServiceImpl();
vacancyService.FindVacancy("test");
}
/* deleted */
#Transactional
public void LoadDataBase() {
VacancyDAO.LoadDataBase(query);
}
#Transactional
public void FindVacancy(String queries) {
VacancyDAO.FindVacancy(sqlQuery);
}
application-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd ">
<context:annotation-config />
<context:property-placeholder location="classpath:jdbc.properties" system-properties-mode="ENVIRONMENT"/>
<context:component-scan base-package="pro.asfert.jobparser.dao"/>
<context:component-scan base-package="pro.asfert.jobparser.service"/>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory">
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value = "${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.databaseurl}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id = "sessionFactory" class = "org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref = "dataSource"/>
<property name="configLocation" value="classpath:hibernate.cfg.xml"/>
<property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.connection.charSet">UTF-8</prop>
</props>
</property>
</bean>
</beans>
hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<mapping class = "pro.asfert.jobparser.domain.Vacancy"></mapping>
</session-factory>
</hibernate-configuration>
Vacancy
package pro.asfert.jobparser.domain;
import javax.persistence.*;
#Entity
#Table(name = "Vacancies")
public class Vacancy {
public Vacancy() {
}
#Id
#Column(name = "id")
#GeneratedValue
private Integer id;
#Column (name = "vacancy")
private String vacancy;
#Column (name = "salary")
private String salary;
#Column (name = "experience")
private String experience;
#Column (name = "education")
private String education;
#Column (name = "employer")
private String employer;
#Column (name = "details")
private String details;
#Column (name = "hr")
private String hr;
#Column (name = "url")
private String url;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getVacancy() {
return vacancy;
}
public void setVacancy(String vacancy) {
this.vacancy = vacancy;
}
public String getSalary() {
return salary;
}
public void setSalary(String salary) {
this.salary = salary;
}
public String getExperience() {
return experience;
}
public void setExperience(String experience) {
this.experience = experience;
}
public String getEducation() {
return education;
}
public void setEducation(String education) {
this.education = education;
}
public String getEmployer() {
return employer;
}
public void setEmployer(String employer) {
this.employer = employer;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public String getHr() {
return hr;
}
public void setHr(String hr) {
this.hr = hr;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
You're creating the service with new here:
public static void main(String[] args) {
VacancyServiceImpl vacancyService = new VacancyServiceImpl();
vacancyService.FindVacancy("test");
}
That way Spring is not involved and does not know anything about this object.
How to fix it:
register your dao and service as spring beans.
initialize the context and get the service from the context and call your method.
ApplicationContext ctx = new ClassPathXmlApplicationContext("application-context.xml");
VacancyServiceImpl serv = ctx.getBean(VacancyServiceImpl.class);
serv.FindVacancy("test");
I have the following 2 objects: User and DomainUser
User.java:
package com.domain;
import java.io.Serializable;
#SuppressWarnings("serial")
public class User implements Serializable {
private long id = 0;
private String userName;
private String password;
public User() {
}
public User(long id) {
this.id = id;
}
public String toString() {
StringBuffer sb = new StringBuffer(256);
sb.append("[id : ").append(id).append(", ");
sb.append("userName : ").append(userName).append(", ");
sb.append("password : ").append(password).append("]");
return sb.toString();
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
DomainUser.java
package com.domain;
import org.springframework.beans.factory.annotation.Autowired;
public class DomainUser {
#Autowired
private User user;
private String domainName;
public String toString() {
StringBuffer sb = new StringBuffer(255);
sb.append(user.toString()).append(", domainName : ").append(domainName);
return sb.toString();
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getDomainName() {
return domainName;
}
public void setDomainName(String domainName) {
this.domainName = domainName;
}
}
I am trying to autowire the User object in to DomainUser by using #Autowired annotation. But when i run the test as below, the User object is not populated.
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="user" class="com.domain.User">
<constructor-arg value="#{1234}"/>
<property name="userName" value="somename" />
<property name="password" value="sompassword" />
</bean>
<bean id="domainUser" class="com.domain.DomainUser">
<property name="domainName" value="mysite" />
</bean>
</beans>
DomainUserTest.java
package com.domain.test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.domain.DomainUser;
public class DomainUserTest {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"applicationContext.xml");
DomainUser domainUser = (DomainUser) context.getBean("domainUser");
System.out.println(domainUser.toString());
}
}
If I autowire using the 'byType' in the autowiring attribute in the applicationContext.xml it works fine :
<bean id="domainUser" class="com.domain.DomainUser" autowire="byType">
<property name="domainName" value="mysite" />
</bean>
Can some one help me understand why doesnt #Autowired annotation produce the same result?
You need an AutowiredAnnotationBeanPostProcessor to handle the injection of #Autowired properties. You could place <context:annotation-config /> (you need to define the context-namespace in your xml) or just define the post processor as a bean in your xml:
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
See for example here for details.