I am working with STS in eclipse Juno ,Spring 3.1.1 ,hibernate 4.1, tomcat 7 and mySQL.
I created a simple MVC template project. my purpose is that the user will enter some data to a form, and that data will
be saved in the database.
I have created:
web layer:
the simple form.
the controller which recieve the data from the form and pass it to the service layer.
service layer:
a service class which contains a DAO field and operate a dao method.
data access layer:
A mock DAO implementation which doesn't commincate with the database.
A Real DAO implementation which doesn commincate with the database.
When i checked the system with the mock DAO implementation, everything was OK - going from the web layer to the mock DAO.
but when injected the real DAO, i just got an 404 error, and nothing in the happened in the Database.
I will show only the DAO implementation and the root-context.xml because this is where i think the problem.
My DAO Implementation:
#Repository
public class Presentation_page_dao_hibernate_Impl implements Presentation_page_dao {
private SessionFactory sessionFactory;
#Autowired
public Presentation_page_dao_hibernate_Impl(SessionFactory sessionFactory) {
this.sessionFactory=sessionFactory;
System.out.println("Hi! i'm in ActionDao_HibernateImpl constructor");
}
private Session currentSession() {
return sessionFactory.getCurrentSession();
}
public void create(Presentation_page pp) {
currentSession().beginTransaction();
currentSession().save(pp);
currentSession().getTransaction().commit();
currentSession().close();
}
public Presentation_page read(int pageid) throws PresentationPageNotFoundException {
currentSession().beginTransaction();
Criteria criteria=currentSession().createCriteria(Presentation_page.class);
criteria.add(Restrictions.eq("page_id", pageid));
List<Presentation_page> list_of_pages=criteria.list();
currentSession().getTransaction().commit();
currentSession().close();
for(Presentation_page pp:list_of_pages) {
if (pp.getPage_id()==pageid){
return pp;
}
}
return null;
}
public void update(Presentation_page pp) throws PresentationPageNotFoundException {
currentSession().beginTransaction();
currentSession().update(pp);
currentSession().getTransaction().commit();
currentSession().close();
}
#Override
public void delete(Presentation_page pp) throws PresentationPageNotFoundException {
currentSession().beginTransaction();
currentSession().delete(pp);
currentSession().getTransaction().commit();
currentSession().close();
}
}
This is my root-context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.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">
<!-- Root Context: defines shared resources visible to all other web components -->
<!-- For annotations -->
<context:component-scan
base-package="my.topLevel.pack">
</context:component-scan>
<import resource="hibernate2.xml"/>
</beans>
This is my hibernate.xml:
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/spring_presentation</property>
<property name="connection.username">rotemya</property>
<property name="connection.password">*******</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<!-- Names the annotated entity class -->
<mapping class="my.topLevel.pack.Domain"/>
</session-factory>
</hibernate-configuration>
I have the following dependencies to the pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>my.topLevel</groupId>
<artifactId>pack</artifactId>
<name>SpringSTS_Sample_Project</name>
<packaging>war</packaging>
<version>1.0.0-BUILD-SNAPSHOT</version>
<properties>
<java-version>1.6</java-version>
<org.springframework-version>3.1.1.RELEASE</org.springframework-version>
<org.aspectj-version>1.6.10</org.aspectj-version>
<org.slf4j-version>1.6.6</org.slf4j-version>
</properties>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
<exclusions>
<!-- Exclude Commons Logging in favor of SLF4j -->
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>3.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.13</version>
</dependency>
</dependencies>
</project>
This are my hibernate jar files:
I'm getting the following error:
java.lang.NoClassDefFoundError: org/hibernate/criterion/Criterion
Any ideas?
Ok-problem solved!
I removed all the jars from the hibernate library file (which i created), and add them all via Maven (the pom.xml file). and the error was gone..
Related
I am getting this error "No Persistence provider for EntityManager named" and not able to proceed.
I am learning hibernate and trying so hands on stuff.
I tried all the methods mentions in this search forum, but still i get the same error. I tried the following
SAVED THE persistent.xml file in src/main/resources/META-INF/persistent.xml.
Updated the provider to "org.hibernate.jpa.HibernatePersistenceProvider".
Still no luck, can any one kindly help in how to resolve this. Below is screen shot and code.
POM:
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate.javax.persistence/hibernate-jpa-2.0-api -->
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.1.0.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.44</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.1</version>
</dependency>
</dependencies>
persistence.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<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="concretepage">
<description>JPA Demo</description>
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/testDB1"/>
<property name="javax.persistence.jdbc.user" value="xxxxx"/>
<property name="javax.persistence.jdbc.password" value="yyyyy"/>
</properties>
</persistence-unit>
</persistence>
Java:
package database.hibernate;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class JPAUtility {
private static final EntityManagerFactory emFactory;
static {
emFactory = Persistence.createEntityManagerFactory("concretepage");
}
public static EntityManager getEntityManager(){
return emFactory.createEntityManager();
}
public static void close(){
emFactory.close();
}
}
Java Program calling JPAUtility:
public class App2 {
public static void main(String[] args) {
EntityManager entityManager = JPAUtility.getEntityManager();
entityManager.getTransaction().begin();
....
entityManager.getTransaction().commit();
}
}
Error Message:
Exception in thread "main" java.lang.ExceptionInInitializerError
at database.hibernate.App2.main(App2.java:9)
Caused by: javax.persistence.PersistenceException: No Persistence provider for EntityManager named concretepage
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:61)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
at database.hibernate.JPAUtility.<clinit>(JPAUtility.java:9)
... 1 more
Project Structure:
You need to change the maven dependency version from <version>6.1.0.Final</version> to <version>5.2.11.Final</version> for <artifactId>hibernate-core</artifactId> as there has been significant changes from Hibernate 5 to 6 and need to consider upgrading corresponding dependencies and schema names etc in persistance.xml file
You can read another thread here - why is dependency to javax.persistence-api removed in hibernate-core 6.0.2
When I tried with 6.1.0.Final - I also get the same error as mentioned below.
But when I changed version back to 5.2.11 then it connected to database.
PS : I've used the maria db instead of mysql but that should not matter.
I want to set session factory in DAO class but after execution I got this issue. In my class i am setting sessionFactory variable through #Autowired annotation but it is not able to set the session Factory.
***************************
APPLICATION FAILED TO START
***************************
Description:
Field sessionFactory in com.springboot.webcrud.dao.ClienteDao required a bean of type 'org.hibernate.SessionFactory' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'org.hibernate.SessionFactory' in your configuration.
Process finished with exit code 1
WHEN I REMOVE THE #Autowired ANNOTATION THEN THE SESSION FACTORY IS ALWAYS NULL WHEN I TRY TO GET THE CURRENT SESSION
This is my project structure: project structure
pom.xml file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.springboot</groupId>
<artifactId>webcrud</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mvc</name>
<packaging>war</packaging>
<description>WEB CRUD</description>
<properties>
<java.version>16</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<!--<scope>provided</scope>-->
</dependency>
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<!--Dependencias de desarrollo -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
<scope>provided</scope>
</dependency>
<!--Dependencias base de datos -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties file
I'm not able to serve the jsp files without declaring this in the properties file. I fear the hibernate configuration is not properly set since the servlet.xml file seems not to be enough. I don't get why the servlet.xml file is not enough
spring.mvc.view.prefix = /WEB-INF/jsp/
spring.mvc.view.suffix = .jsp
web.xml file
<?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"
id="WebApp_ID" version="3.1">
<display-name>MVC APP</display-name>
<absolute-ordering />
<!-- Configuracion del dispatcher servlet -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Ubicacion URL del servlet -->
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
servlet.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:context="http://www.springframework.org/schema/context"
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/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- Paquete de escaneo de componentes -->
<context:component-scan base-package="com.springboot.webcrud"/>
<!-- Conversión formateo y validación-->
<mvc:annotation-driven/>
<!-- Configuración Spring MVC directorio view -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- Origen BBDD y connection pool -->
<bean id="dataSource" name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="com.mysql.cj.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/tienda?useSSL=false&serverTimezone=UTC"/>
<property name="user" value="root"/>
<property name="password" value="BaseDeDatos2022"/>
<!-- Propiedades connection pool para C3P0 -->
<property name="minPoolSize" value="5"/>
<property name="maxPoolSize" value="20"/>
<property name="maxIdleTime" value="30000"/>
</bean>
<!-- Configuración Hibernate session factory -->
<bean id="sessionFactory" name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.springboot.webcrud.entity"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="ClienteDao" name="ClienteDao" class="com.springboot.webcrud.dao.ClienteDao">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="hibernateTemplate" name="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- Configuración Hibernate transaction manager -->
<bean id="txManager" name="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- Habilitar configuración de transacciones basadas en anotaciones -->
<tx:annotation-driven transaction-manager="txManager"/>
</beans>
Entity class
package com.springboot.webcrud.entity;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
#Setter
#Getter
#ToString
#Entity
#Table(name = "clientes")
public class Cliente {
public Cliente() {
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
String id;
#Column(name = "nombre")
String nombre;
#Column(name = "apellido")
String apellido;
#Column(name = "email")
String email;
}
DAO Class
When I remove the #Autowired annotation then the sessionFactory is always null when I try to get the current session
package com.springboot.webcrud.dao;
import com.springboot.webcrud.entity.Cliente;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import javax.transaction.Transactional;
import java.util.List;
#Repository
public class ClienteDao implements IClienteDao {
#Autowired
private SessionFactory sessionFactory;
#Override
#Transactional
public List<Cliente> listarClientes() {
if (sessionFactory == null) {
System.out.println("SESION NULA");
return null;
}
Session session = sessionFactory.getCurrentSession();
System.out.println("SESION OK");
Query<Cliente> query = session.createQuery("from Cliente", Cliente.class);
return query.getResultList();
}
}
Controller class
package com.springboot.webcrud.controller;
import com.springboot.webcrud.dao.IClienteDao;
import com.springboot.webcrud.entity.Cliente;
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 java.util.List;
#Controller
#RequestMapping("/tienda")
public class TiendaController {
#Autowired
IClienteDao servicioCliente;
#RequestMapping("/clientes")
public String listarClientes(Model model) {
System.out.println("Página de clientes");
List<Cliente> clientes = servicioCliente.listarClientes();
model.addAttribute("clientes", clientes);
for (Cliente cliente : clientes
) {
System.out.println(cliente.toString());
}
return "listaClientes";
}
}
Please I appreciate your help I've been stuck here for several days.
When I run the main class then this error pop up. I have checked most of the links for this issue but couldn't solve the problem. Please check the following files to get some idea about the problem Thanks in advance.
# bean.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"
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-3.2.xsd">
<context:property-placeholder
location="com/springproject/test/springtest01/props jdbc.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<context:component-scan
base-package="com.springproject.test.springtest01">
</context:component-scan>
</beans>
#pom.xml#
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.springproject.test</groupId>
<artifactId>springtest01</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springtest01</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.2.18.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>3.2.18.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.18.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.5</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>3.2.18.RELEASE</version>
</dependency>
</dependencies>
</project>
#NoticesDao#
package com.springproject.test.springtest01;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
#Component("noticeDao")
public class NoticesDAO {
private JdbcTemplate jdbc;
#Autowired
public void setDataSource(DataSource jdbc) {
this.jdbc = new JdbcTemplate(jdbc);
}
public List<Notice> getNotices() {
return jdbc.query("select * form notices", new RowMapper<Notice>() {
public Notice mapRow(ResultSet rs, int rowNum) throws SQLException {
Notice notice = new Notice();
notice.setId(rs.getInt("id"));
notice.setName(rs.getString("name"));
notice.setEmail(rs.getString("email"));
notice.setText(rs.getString("text"));
return notice;
}
});
}
}
#jdbc.properties#
jdbc.username = root
jdbc.password = 123456
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/springtutorial
#Main#
public class App
{
public static void main( String[] args )
{
try{
ApplicationContext context = new ClassPathXmlApplicationContext("com/springproject/test/springtest01/beans/beans.xml");
NoticesDAO noticesDAO = (NoticesDAO) context.getBean("noticeDao");
List<Notice> notices = noticesDAO.getNotices();
for(Notice notice: notices){
System.out.println(notice);
}
((ClassPathXmlApplicationContext)context).close();
}catch(Exception e){
System.out.println("==========="+e);
}
}
}
First, your SQL request is invalid, it should be select * FROM notices not FORM.
Second, I didn't manage to get the same error as you. In fact, I could not even make the application context to find the bean.xml and jdbc.properties files with your current configuration. I changed some configuration as follows:
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
and
<context:property-placeholder location="jdbc.properties" />
put the files in a main/resources directory, then built and successfully ran the project with
mvn clean compile
mvn mvn exec:java -Dexec.mainClass="com.springproject.test.springtest01.App"
I'm doing a GWTP project and use Spring Data JPA for a connection with an oracle database. I've read several tutorials in which a repository interface is used directly without the use of implementation. It was #Autowired where needed and it worked fine. I've tried to use the same strategy but it seems the #Autowired annotation is not working at all.
Here is my Repository :
#Repository
public interface BugRepository extends JpaRepository<Bug, Long> {
List<Bug> findAll();
.....
}
I try to inject it with #Autowired in my service implementation (I use RESTful services) :
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
#Path("/bugs")
#Component
public class BugServiceImpl{
#Autowired
private BugRepository bugRepository;
#GET
#Path("/findAll")
public List<Bug> findAll() {
return bugRepository.findAll();
}
}
Here is my Entity :
#Entity
#Table(name = "BUGS")
#SequenceGenerator(name = "BUG_SEQUENCE", sequenceName = "BUG_SEQUENCE")
public class Bug implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "BUG_SEQUENCE")
#Column(name="BUG_ID")
private Long bugId;
#Column(name="BUG_NAME")
private String bugName;
#OneToOne
#PrimaryKeyJoinColumn
#Column(name="CREATED_BY")
private User createdBy;
#OneToOne
#PrimaryKeyJoinColumn
#Column(name="ASSIGNED_TO")
private User assignedTo;
#Column(name="CREATION_DATE")
private Date creationDate;
#Column(name="LAST_UPDATE_DATE")
private Date lastUpdateDate;
#Column(name="BUG_COMMENT")
private String bugComment;
#OneToOne(cascade = CascadeType.ALL, optional = false, fetch = FetchType.EAGER, orphanRemoval = true)
#PrimaryKeyJoinColumn
#Column(name="PRIORITY_ID")
private Priority priority;
#OneToOne
#PrimaryKeyJoinColumn
private Status status;
public Bug() {
}
}
I also have applicationContext.xml and persistence.xml in main/resources/META-INF. Here is my applicationContext.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
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
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.1.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">
<context:component-scan base-package="com.edu" />
<jpa:repositories base-package="com.edu.server.repositories" />
<context:annotation-config />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver" />
<property name="url" value="***"/>
<property name="username" value="***"/>
<property name="password" value="***"/>
</bean>
<!-- EntityManagerFactory -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:packagesToScan="com.edu.shared.entity"
p:dataSource-ref="dataSource"
>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="generateDdl" value="true" />
<property name="showSql" value="false" />
</bean>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
My persistence.xml :
<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">
<!-- oracle -->
<persistence-unit name="oracle">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.edu.server.service.BugServiceImpl</class>
<class>com.edu.server.repositories.BugRepository</class>
<class>com.edu.shared.entity.Bug</class>
<properties>
<property name="hibernate.archive.autodetection" value="class" />
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
<property name="hibernate.connection.driver_class" value="oracle.jdbc.OracleDriver" />
<property name="hibernate.connection.url" value="***" />
<property name="hibernate.connection.username" value="***" />
<property name="hibernate.connection.password" value="***" />
<property name="hibernate.flushMode" value="FLUSH_AUTO" />
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
And finally the exception I get is :
java.lang.NullPointerException
com.edu.server.service.BugServiceImpl.findAll(BugServiceImpl.java:39)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:606)
...
When I debug the code and put a breakpoint to the autowired repository it appears to be null so I suppose it's not injected properly and that's why invoking the method findAll fires the NullPointerException. So, why do you think the #Autowired annotation is not working?
I think you're mixing two ways of Spring/JPA configuration. Last time when i configured Spring/JPA project with XML I use only DataSource bean without persistence.xml configuration for connection to the database. I can suggest you to read the official documentation of Spring Data. The community has one of the best documentation.
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/orm.html
First problem that i see is you have annotated your interface with #Repository
You shouldn't do that, but as follows:
//no annotation here
public interface BugRepository extends JpaRepository<Bug, Long> {
List<Bug> findAll();
.....
}
Secondly, make sure your BugRepository interface is in the package below, or else it wont work:
<jpa:repositories base-package="com.edu.server.repositories" />
Third thing i noticed is in your persistance.xml, you have noted NOT only #Entity beans, but #Service and a #Repository. You are supposed to only have #Entity beans (which are to be managed)
Lastly, you seem to be mixing Spring and Jersey, so make sure you have your Spring container (application/web context) properly set up, so it can manage (inject) your beans/repos/services.
I want to thank all for the help. I solved my problem. There were problems in my configuration files.
First of all, I really didn't need any persistence.xml because I've created a dataSource bean in my applicationContext.xml which contains all of the needed information regarding the connection with my database. You shouldn't mix the both things, I suppose.
Secondly, you should properly configure the link between Spring and Jersey. I had to add some new dependencies in my pom.xml which were needed for linking Spring and Jersey (there is a jersey-spring3 dependency which I didn't know existed). So, now all of the dependencies I use, concerning Spring and Jersey are these:
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>${javax.rs.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.fusesource.restygwt</groupId>
<artifactId>restygwt</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>io.spring.platform</groupId>
<artifactId>platform-bom</artifactId>
<version>1.1.2.RELEASE</version>
<type>pom</type>
<!--<scope>import</scope>-->
<scope>compile</scope>
</dependency>
<!-- DataSource (HikariCP) -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>2.2.5</version>
</dependency>
<!-- JPA Provider (Hibernate) -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.8.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.10.2.RELEASE</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>12.1.0.2</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.8.Final</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring3</artifactId>
<version>${jersey.version}</version>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</exclusion>
</exclusions>
</dependency>
In addition, I had to configure my web.xml so that Jersey could read the applicationContext.xml. Without configuring my web.xml the applicationContext.xml was useless and that's why the annotations and the connection with the database didn't work. Here is my web.xml :
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:META-INF/applicationContext.xml</param-value>
</context-param>
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>
org.glassfish.jersey.servlet.ServletContainer
</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.edu</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
As far as I understood the ContextLoadListener makes sure the web configuration "listens" for other configuration xml files and that's how the applicationContext.xml is now read and used. And with these settings
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.edu</param-value>
I make sure that my packages would be scanned for #Provider and #Path annotations and without these piece of my code my services would not be active.
More about this Provider Packages setting can be read here :
https://jersey.java.net/apidocs/2.23.2/jersey/org/glassfish/jersey/server/ServerProperties.html#PROVIDER_PACKAGES
I hope my issue and this answer are useful for all with similar configuration problems.
I downloaded the spring batch admin application in the github repo and I imported it in eclipse. it works perfectly.
Then, I asked myself how to import an external config file into the application that I can use in my job definition class.
I tried this :
VM Arguments
-Dspring.config.location=C:/path/to/config/file/application.properties
Job configuration
src/main/java
org.springframework.batch.admin.sample.job
-------------------------------------------
#Configuration
public class JobConfiguration {
//I try to import this properties from an external config file.
#Value("${folder.input.files}")
private String pathToFiles;
#Autowired
public JobBuilderFactory jobBuilderFactory;
#Autowired
public StepBuilderFactory stepBuilderFactory;
#Bean
#JobScope
public ExampleItemReader itemReader() {
return new ExampleItemReader();
}
#Bean
#StepScope
public ExampleItemWriter itemWriter(#Value("#{jobParameters[fail]}") Boolean fail) {
ExampleItemWriter itemWriter = new ExampleItemWriter();
itemWriter.setFail(fail);
return itemWriter;
}
#Bean
public Step step1() {
return stepBuilderFactory.get("step1")
.<String, Object>chunk(5)
.reader(itemReader())
.writer(itemWriter(null))
.build();
}
#Bean
public Job javaJob() {
return jobBuilderFactory.get("javaJob")
.start(step1())
.build();
}
}
XML configuration
src/main/resources
launch-context.xml
-----------------------
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p" 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">
<description><![CDATA[
A convenient aggregating config file for running the jobs in this project
from the command line instead of from the web application. E.g.
$ MAVEN_OPTS="-Dbatch.jdbc.url=jdbc:hsqldb:hsql://localhost:9005/samples -Dbatch.data.source.init=false" \
mvn exec:java -Dexec.classpathScope=runtime \
-Dexec.mainClass=org.springframework.batch.core.launch.support.CommandLineJobRunner \
-Dexec.args="classpath:launch-context.xml job1 fail=false run.id=1"
]]>
</description>
<import resource="classpath*:/META-INF/spring/batch/bootstrap/**/*.xml" />
<import resource="classpath*:/META-INF/spring/batch/override/**/*.xml" />
<bean id="jobLauncherTaskExecutor" class="org.springframework.core.task.SyncTaskExecutor"/>
<!-- Try to add my external config file -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:file:///${spring.config.location}</value>
</list>
</property>
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="ignoreResourceNotFound" value="true" />
<property name="ignoreUnresolvablePlaceholders" value="false" />
<property name="order" value="1" />
</bean>
</beans>
Stack trace when I launch the app with tomcat 7
18:54:38,528 ERROR localhost-startStop-1 context.ContextLoader:331 - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.lang.String org.springframework.batch.admin.sample.job.JobConfiguration.pathToFiles; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'folder.input.files' in string value "${folder.input.files}"
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1204)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:229)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:762)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.batch.core.configuration.support.GenericApplicationContextFactory$ResourceAnnotationApplicationContext.<init>(GenericApplicationContextFactory.java:209)
at org.springframework.batch.core.configuration.support.GenericApplicationContextFactory.createApplicationContext(GenericApplicationContextFactory.java:70)
at org.springframework.batch.core.configuration.support.AbstractApplicationContextFactory.createApplicationContext(AbstractApplicationContextFactory.java:172)
at org.springframework.batch.core.configuration.support.DefaultJobLoader.doLoad(DefaultJobLoader.java:154)
at org.springframework.batch.core.configuration.support.DefaultJobLoader.load(DefaultJobLoader.java:147)
at org.springframework.batch.core.configuration.support.AutomaticJobRegistrar.start(AutomaticJobRegistrar.java:173)
at org.springframework.batch.core.configuration.support.AutomaticJobRegistrar.onApplicationEvent(AutomaticJobRegistrar.java:139)
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:151)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:128)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:331)
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:773)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:483)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4939)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5434)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.lang.String org.springframework.batch.admin.sample.job.JobConfiguration.pathToFiles; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'folder.input.files' in string value "${folder.input.files}"
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:555)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 34 more
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'folder.input.files' in string value "${folder.input.files}"
at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:174)
at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126)
at org.springframework.beans.factory.config.PropertyPlaceholderConfigurer$PlaceholderResolvingStringValueResolver.resolveStringValue(PropertyPlaceholderConfigurer.java:259)
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveEmbeddedValue(AbstractBeanFactory.java:800)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:962)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:949)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:527)
... 36 more
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-batch-admin-sample</artifactId>
<description>A sample web application (WAR project) for Spring Batch Admin console.</description>
<parent>
<artifactId>spring-batch-admin-parent</artifactId>
<groupId>org.springframework.batch</groupId>
<version>2.0.0.BUILD-SNAPSHOT</version>
<relativePath>../spring-batch-admin-parent</relativePath>
</parent>
<packaging>war</packaging>
<name>Web Sample</name>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-infrastructure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-admin-manager</artifactId>
<version>2.0.0.BUILD-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-admin-resources</artifactId>
<version>2.0.0.BUILD-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
<configuration>
<contextPath>/spring-batch-admin-sample</contextPath>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Maven Milestone Repository</name>
<url>http://s3.amazonaws.com/maven.springframework.org/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
</project>
I tried this post and much more but without success.
I use exactly the same files and the same configuration than the spring batch admin github project.
Can someone tell me how to add the external configuration file to spring batch admin?
Spring batch admin searches configurations in specific paths.This page explains from which paths it loads resources:
<import resource="classpath*:/META-INF/spring/batch/bootstrap/**/*.xml"/>
<import resource="classpath*:/META-INF/spring/batch/override/**/*.xml"/>
Note that the "override" location has no files in it in Spring Batch
Admin distribution. This is a placeholder for users to add their own
content.
We managed to load external properties files placing xml configuration file under src/main/resources/META-INF/spring/batch/override/manager/env-context.xml which looks like this:
<?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.xsd">
<!-- Use this to set additional properties on beans at run time -->
<bean id="placeholderProperties"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:/org/springframework/batch/admin/bootstrap/batch.properties</value>
<value>classpath:batch-default.properties</value>
<value>classpath:batch-${ENVIRONMENT:hsql}.properties</value>
<value>classpath:batch-${ENVIRONMENT:mysql}.properties</value>
<!-- here we load properties from external config folder -->
<value>file:${spring.file.location}</value>
</list>
</property>
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="ignoreResourceNotFound" value="false" />
<property name="ignoreUnresolvablePlaceholders" value="false" />
<property name="order" value="1" />
</bean>
</beans>
Under main folder of spring-batch-admin template, there are three folders - java, resources and webapp. Under resources there are some property files and META-INF folder. within META-INF there are two folders - batch and servlet.
Here If I want to add new property file "batch.properties" under resources and want to refer the property values from configuration (xml) files from "META-INF/batch/*.xml" in addition to the properties from spring-batch-admin-manager-1.0.0.M1.jar,
1. where to add below entries
Where to keep "env-context.xml". Under which folders, coz in "src/main/resources/META-INF" i can see only one folder batch.
I tried to create "spring/batch/override/manager/env-context.xml" under "src/main/resources/META-INF" but not able to read the property file entries.
If you provide your working application folder structure will help me a lot.
You can put your env-context.xml file on spring/batch/servlet/override/env-context.xml folder.