Spring #Autowired annotation doesn't work in Java TimerTask - java

How to change my code to make it work?
public class GetDataFromTheWarehouse implements ServletContextListener {
#Autowired
ScheduledTask scheduledTask;
private ScheduledExecutorService scheduler = null;
public GetDataFromTheWarehouse() {
}
public void contextDestroyed(ServletContextEvent arg0) {
try {
System.out.println("Scheduler Shutting down successfully " + new Date());
scheduler.shutdown();
} catch (Exception ex) {
}
}
public void contextInitialized(ServletContextEvent arg0) {
if ((scheduler == null) || (!scheduler.isTerminated())) {
scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(scheduledTask, 0, 60*60, TimeUnit.SECONDS);
}
}
}
Following is the ScheduledTask class, in which productService is null, so will fail every time calling productService.save():
#Component
public class ScheduledTask extends TimerTask {
#Autowired
ProductService productService;
public void run() {
try {
parse();
} catch (IOException e) {
e.printStackTrace();
}
}
public void parse() throws IOException {
...
productService.save(product);
...
}
}
}
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:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- Enable autowire -->
<context:component-scan base-package="com" />
<context:annotation-config />
<bean id="usersUpdateTask" class="com.demo.task.ScheduledTask">
</bean>
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:resources mapping="/views/**" location="/views/" />
<mvc:resources mapping="/img/**" location="/img/" />
<mvc:resources mapping="/fonts/**" location="/fonts/" />
<mvc:resources mapping="/css/**" location="/css/" />
<mvc:resources mapping="/js/**" location="/js/" />
<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/demo" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<!-- Session Factory Declaration -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.demo.model" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.enable_lazy_load_no_trans">true</prop>
<prop key="hibernate.default_schema">demo</prop>
<prop key="format_sql">true</prop>
<prop key="use_sql_comments">true</prop>
<!-- <prop key="hibernate.hbm2ddl.auto">create</prop> -->
</props>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
My demo structure:

Why do you have ScheduledTask initialized in appilcationConfig.xml when you are already using #Component for that bean class. Remove this from your applicationContext.xml file.
<bean id="usersUpdateTask" class="com.demo.task.ScheduledTask">
</bean>
EDIT : Adding Spring Boot Sample.
Here is the sample code for #Scheduled with #Autowired in Spring Boot.
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>springboot-scheduler</groupId>
<artifactId>springboot-scheduler-app</artifactId>
<version>1.0.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
</dependencies>
</project>
MySpringBootApp.java
package my.spring.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
#SpringBootApplication
#EnableScheduling
public class MySpringBootApp {
public static void main(String[] args) {
SpringApplication.run(new Object[] { MySpringBootApp.class }, args);
}
}
MyService.java
package my.spring.app;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.stereotype.Component;
#Component
public class MyService {
public String getNextMessage(){
return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(new Date());
}
}
ScheduledTask.java
package my.spring.app;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
#Component
public class ScheduledTask {
#Autowired
MyService service;
#Scheduled(fixedRate = 5000)
public void process() {
System.out.println("Processing at " + service.getNextMessage());
}
}
Sample output
Processing at 2016-08-24T14:01:48
Processing at 2016-08-24T14:01:53
Processing at 2016-08-24T14:01:58
Hope this helps.
EDIT-2 : Adding Spring Boot Sample war file version. Tested with Tomcat 8.
Following two files are changed. Others are same as above.
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>springboot-scheduler</groupId>
<artifactId>springboot-scheduler-app</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>war</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
MySpringBootApp.java
package my.spring.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.scheduling.annotation.EnableScheduling;
#SpringBootApplication
#EnableScheduling
public class MySpringBootApp extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(MySpringBootApp.class);
}
public static void main(String[] args) {
SpringApplication.run(new Object[] { MySpringBootApp.class }, args);
}
}

Related

Spring AOP not being applied

I trying to apply MethodBeforeAdvice but unable to do so. I am unable to figure out what is wrong with it. Please help me with it.
//Interface
package org.mycode;
public interface IHello {
boolean authenticate(String input);
}
//Class on which advice need to be applied
package org.mycode;
public class HelloImpl implements IHello {
#Override
public boolean authenticate(String input) {
System.out.println("authecated successfully");
System.out.println(System.currentTimeMillis());
System.out.println(input);
return true;
}
}
}
//Advice class
package org.mycode;
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
public class MethodAdvice1 implements MethodBeforeAdvice {
#Override
public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable {
System.out.println("checking for authentication of the caller");
System.out.println(arg0.getName());
System.out.println(arg0.getDeclaringClass().getName());
System.out.println(arg1);
System.out.println("time start: " + System.currentTimeMillis());
}
}
//Client for the Adviced class
package org.mycode;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class AdviceManager {
public static void main(String[] args) {
ClassPathResource cp = new ClassPathResource("org/mycode/config.xml");
BeanFactory factory = new XmlBeanFactory(cp);
HelloImpl hil = (HelloImpl) factory.getBean("myClass");
System.out.println(hil.authenticate("AdvicedMethod"));
}
}
//Config file
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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<bean id="advice1" class="org.mycode.MethodAdvice1"></bean>
<bean id="myClass" class="org.mycode.HelloImpl"></bean>
<bean id="aspect1"
class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
<property name="advice" ref="advice1"></property>
<property name="pattern">
<value>.*</value>
</property>
</bean>
<bean id="advicedHello" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<value>org.mycode.IHello</value>
</property>
<property name="target" ref="myClass" />
<property name="interceptorNames">
<list>
<value>aspect1</value>
</list>
</property>
</bean>
</beans>
output on running
INFO: Loading XML bean definitions from class path resource [org/mycode/config.xml]
authecated successfully
1467340328875
AdvicedMethod
true

Java NoSuchMethodException In Spring (While I have created a constructor)

I would like to ask about where did I go wrong in this. I just started up a simple login feature using Spring and Hibernate 4, but it seems that I always seem to get NoSuchMethodException. Tried looking up everywhere about where I go wrong, but it's like I never did get it right. Any help will be most appreciated. Below are the Codes.
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"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="transactionInterceptor"
class="org.springframework.transaction.interceptor.TransactionInterceptor">
<property name="transactionManager" ref="transactionManager" />
<property name="transactionAttributes">
<props>
<prop key="save*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="update*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="delete*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="try*">PROPAGATION_REQUIRED,ISOLATION_READ_UNCOMMITTED,-Exception</prop>
<!-- <prop key="try*">PROPAGATION_REQUIRED,ISOLATION_SERIALIZABLE,-Exception</prop> -->
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="dataSource" ref="dataSource" />
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url"
value="jdbc:oracle:thin:#db01.aprdev.com:1521:aprdev" />
<property name="username" value="training" />
<property name="password" value="training" />
<property name="initialSize" value="5" />
<property name="maxActive" value="10" />
</bean> -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<property name="url"
value="jdbc:sqlserver://localhost:1433;databaseName=test" />
<property name="username" value="sa" />
<property name="password" value="pass123" />
<property name="initialSize" value="5" />
<property name="maxActive" value="10" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>com/model/User.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<!-- <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop> -->
<prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
</props>
</property>
</bean>
<bean id="userDAO" class="com.dao.impl.UserDAOImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="serviceProxyTemplate" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="interceptorNames">
<list>
<value>transactionInterceptor</value>
</list>
</property>
</bean>
<bean id="userServiceProxy" parent="serviceProxyTemplate">
<property name="target">
<bean id="userService" class="com.services.impl.UserServiceImpl">
<property name="userDAO" ref="userDAO" />
</bean>
</property>
</bean>
User.java
package com.model;
public class User {
private String id;
private String name;
private String password;
public User() {}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
UserServiceImpl.java
package com.services.impl;
import java.util.List;
import com.dao.UserDAO;
import com.model.User;
import com.services.UserService;
public class UserServiceImpl implements UserService {
private UserDAO userDAO;
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
#Override
public List validate(String name, String password) {
User user = new User();
user.setName(name);
user.setPassword(password);
return this.userDAO.validate(user);
}
}
UserDAOImpl.java
package com.dao.impl;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.dao.UserDAO;
import com.model.User;
public class UserDAOImpl implements UserDAO{
private SessionFactory sessionFactory;
public UserDAOImpl(SessionFactory session) {
this.sessionFactory = session;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Override
public List validate(User user) throws HibernateException {
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("from User where name = :name and password = :pass ");
query.setParameter("name", user.getName());
query.setParameter("pass", user.getPassword());
return query.list();
}
}
Test.java
package com.factory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.services.UserService;
public class SpringUtil {
private static ApplicationContext applicationContext;
public static ApplicationContext getApplicationContext(){
if(applicationContext==null){
applicationContext = new ClassPathXmlApplicationContext("com/factory/bean.xml");
}
return applicationContext;
}
public static UserService getUserService(){
return (UserService) getApplicationContext().getBean("userServiceProxy");
}
}
Help will be much appreciated. Thank you very much!
Not sure if I've answered the problem.
Here is my test
package com.services.impl;
import static org.junit.Assert.assertEquals;
import java.util.List;
import javax.transaction.Transactional;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.model.User;
import com.model.UserDAO;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = "classpath:applicationContext-test.xml")
public class StudyPointRepositoryTest {
#Autowired
private UserServiceImpl userService;
#Autowired
private UserDAO dao;
#Test
#Transactional
public void test1() {
dao.save(makeUser("Fred", "pass1"));
dao.save(makeUser("Bill", "pass2"));
dao.save(makeUser("Nobby", "pass3"));
List<User> validate = userService.validate("Fred", "pass1");
assertEquals(1, validate.size());
validate = userService.validate("Fred", "wrongpass");
assertEquals(0, validate.size());
}
private User makeUser(String name, String password) {
User user = new User();
user.setName(name);
user.setPassword(password);
return user;
}
}
Here is my config for test
<?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:jpa="http://www.springframework.org/schema/data/jpa" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com" />
<jdbc:embedded-database id="dataSource" type="H2" />
<tx:annotation-driven />
<jpa:repositories base-package="com.model" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.model" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">create</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
</beans>
Here is my DAO
package com.model;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface UserDAO extends CrudRepository<User, Integer> {
List<User> findByNameAndPassword(String name, String password);
}
Here is my Service
package com.services.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.model.User;
import com.model.UserDAO;
#Service
public class UserServiceImpl {
#Autowired
private UserDAO userDAO;
public List<User> validate(String name, String password) {
return userDAO.findByNameAndPassword(name, password);
}
}
And here is my pom, probable stuff that not needed
<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>com.greg</groupId>
<artifactId>jpa</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>fmis Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<spring.version>4.2.4.RELEASE</spring.version>
<spring.data.version>1.9.2.RELEASE</spring.data.version>
<hibernate.version>5.0.6.Final</hibernate.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${spring.data.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.190</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.3</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.13</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>javax.transaction-api</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<finalName>jpaTest</finalName>
</build>
</project>

org.springframework.beans.factory.BeanCreationException... java.lang.NoClassDefFoundError: com/atomikos/diagnostics/Console

I am getting
org.springframework.beans.factory.BeanCreationException....java.lang.NoClassDefFoundError:
com/atomikos/diagnostics/Console
Main.java
package com.nody.client;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.nody.spring.global.AccountInter;
public class Main {
public static void main(String arg[]) throws Exception
{
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
Object o=ctx.getBean("accimpl");
AccountInter inter=(AccountInter)o;
inter.transferMoney(101,102,2000);
}
}
Here is my Interface
AccountInter.java
package com.nody.spring.global;
public interface AccountInter {
void transferMoney(int accno1,int accno2,int amount) throws Exception;
}
Here is Implement class AccountImpl.java
package com.nody.spring.global;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;
public class AccountImpl implements AccountInter {
private JdbcTemplate jt1;
private JdbcTemplate jt2;
public void setJt1(JdbcTemplate jt1) {
this.jt1 = jt1;
}
public void setJt2(JdbcTemplate jt2) {
this.jt2 = jt2;
}
#SuppressWarnings("deprecation")
#Override
#Transactional(timeout=5)
public void transferMoney(int accno1, int accno2, int amount) throws Exception
{
int s1=jt1.queryForInt("select bal from Account1 where acno=?",accno1);
//Deducting amount from balance
int s2=s1-amount;
if(s2<500)
{
throw new Exception();
}
int s3=jt2.queryForInt("select bal from Account2 where accno=?",accno2);
//adding amount to account2
int s4=s3+amount;
jt1.update("update Account1 set bal=? where accno=?",s2,accno1);
jt2.update("update Account2 set bal=? where accno=?",s4,accno2);
System.out.println("Transaction Successfull !");
}
}
Here is applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!--- Business bean Configuration -->
<bean id="accimpl" class="com.nody.spring.global.AccountImpl">
<property name="jt1" ref="jt1"></property>
<property name="jt2" ref="jt2"></property>
</bean>
<!--JdbcTemplate -->
<bean id="jt1" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds1"></property>
</bean>
<bean id="jt2" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds2"></property>
</bean>
<!-- -DataSource Configuration DATABASE-1 -->
<bean id="ds1" class="com.atomikos.jdbc.AtomikosDataSourceBean" init-method="init" destroy-method="close">
<property name="uniqueResourceName" value="A"></property>
<property name="xaDataSourceClassName" value="oracle.jdbc.xa.client.OracleXADataSource"></property>
<property name="xaProperties">
<props>
<prop key="databaseName">xe</prop>
<prop key="user">scott</prop>
<prop key="password">tiger</prop>
<prop key="URL">jdbc:oracle:thin:#localhost:1521:xe</prop>
</props>
</property>
<property name="poolSize" value="1"></property>
</bean>
<!-- DataSource Configuration DATABASE2 -->
<bean id="ds2" class="com.atomikos.jdbc.AtomikosDataSourceBean" init-method="init" destroy-method="close">
<property name="uniqueResourceName" value="B"></property>
<property name="xaDataSourceClassName" value="com.mysql.jdbc.jdbc2.optional.MysqlXADataSource"></property>
<property name="xaProperties">
<props>
<prop key="databaseName">nody</prop>
<prop key="user">root</prop>
<prop key="password"></prop>
<prop key="URL">jdbc:mysql://localhost:3306/nody</prop>
</props>
</property>
<property name="poolSize" value="1"></property>
</bean>
<bean id="atomikosTransactionManager" class="com.atomikos.icatch.jta.UserTransactionManager" init-method="init" destroy-method="close">
</bean>
<bean id="txm" class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="transactionManager">
<ref bean="atomikosTransactionManager"></ref>
</property>
</bean>
<tx:annotation-driven transaction-manager="txm"/>
</beans>
Here my application Directory structure
aopalliance.jar
aspectjrt-1.8.5.jar
aspectj-weaver.jar
atomikos-transactions-api.jar
atomikos-transactions-jta.jar
atomikos-util-4.0.0M4.jar
commons-logging-api-1.1.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
Here is complete Exception details
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jt1' defined in class path resource [applicationContext.xml]: Cannot resolve reference to bean 'ds1' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ds1' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: com/atomikos/diagnostics/Console
I am really tried but not getting what happening. Please help me.
The runtime cannot find the class com.atomikos.diagnostics.Console on the class path.
If you are building with Maven, add this dependency:
<dependency>
<groupId>com.atomikos</groupId>
<artifactId>atomikos-util</artifactId>
<version>3.7.1</version>
</dependency>
http://mvnrepository.com/artifact/com.atomikos/atomikos-util
Otherwise download the atomikos-util.jar from this site and add it to your class path.
Edit: 3.7.1 seems to be the last version with the Console class in it
Download from http://mvnrepository.com/artifact/com.atomikos/atomikos-util/3.7.1

How to secure a Spring soap service with certificates

I managed to create a soap server and client that requires a username and password to call functions. The following code shows how i've done this
Client:
package hello;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.ws.client.support.interceptor.ClientInterceptor;
import org.springframework.ws.soap.security.xwss.XwsSecurityInterceptor;
import org.springframework.ws.soap.security.xwss.callback.SpringUsernamePasswordCallbackHandler;
#Configuration
public class SoftlayerConfiguration {
#Bean
public Jaxb2Marshaller marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setContextPath("be.elision.soap.cloud");
return marshaller;
}
#Bean
public SoftlayerClient softlayerClient(Jaxb2Marshaller marshaller) {
SoftlayerClient client = new SoftlayerClient();
client.setDefaultUri("http://192.168.137.107:8080/ws");
client.setMarshaller(marshaller);
client.setUnmarshaller(marshaller);
client.setInterceptors(new ClientInterceptor[]{securityInterceptor()});
return client;
}
#Bean
XwsSecurityInterceptor securityInterceptor() {
XwsSecurityInterceptor securityInterceptor = new XwsSecurityInterceptor();
securityInterceptor.setSecureRequest(true);
securityInterceptor.setValidateRequest(true);
securityInterceptor.setCallbackHandler(callbackHandler());
securityInterceptor.setPolicyConfiguration(new ClassPathResource("securityPolicy.xml"));
return securityInterceptor;
}
#Bean
SpringUsernamePasswordCallbackHandler callbackHandler() {
SecurityContextHolder.setContext(new SecurityContextImpl());
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken("user", "password"));
return new SpringUsernamePasswordCallbackHandler();
}
}
Server:
package be.elision.main;
import java.util.Collections;
import java.util.List;
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.ws.config.annotation.EnableWs;
import org.springframework.ws.config.annotation.WsConfigurerAdapter;
import org.springframework.ws.server.EndpointInterceptor;
import org.springframework.ws.server.endpoint.interceptor.PayloadLoggingInterceptor;
import org.springframework.ws.soap.security.xwss.XwsSecurityInterceptor;
import org.springframework.ws.soap.security.xwss.callback.SimplePasswordValidationCallbackHandler;
import org.springframework.ws.soap.server.endpoint.interceptor.PayloadValidatingInterceptor;
import org.springframework.ws.transport.http.MessageDispatcherServlet;
import org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition;
import org.springframework.xml.xsd.SimpleXsdSchema;
import org.springframework.xml.xsd.XsdSchema;
#EnableWs
#Configuration
public class WebServiceConfig extends WsConfigurerAdapter {
#Bean
public ServletRegistrationBean messageDispatcherServlet(
ApplicationContext applicationContext) {
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext);
servlet.setTransformWsdlLocations(true);
return new ServletRegistrationBean(servlet, "/ws/*");
}
#Bean(name = "devices")
public DefaultWsdl11Definition defaultWsdl11Definition(
XsdSchema devicesSchema) {
DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
wsdl11Definition.setPortTypeName("DevicesPort");
wsdl11Definition.setLocationUri("/ws");
wsdl11Definition.setTargetNamespace("http://elision.be/soap/cloud");
wsdl11Definition.setSchema(devicesSchema);
return wsdl11Definition;
}
// toevoegen van xsd aan bean
#Bean
public XsdSchema devicesSchema() {
return new SimpleXsdSchema(new ClassPathResource("devices.xsd"));
}
#Bean
XwsSecurityInterceptor securityInterceptor() {
XwsSecurityInterceptor securityInterceptor = new XwsSecurityInterceptor();
securityInterceptor.setCallbackHandler(callbackHandler());
securityInterceptor.setPolicyConfiguration(new ClassPathResource(
"securityPolicy.xml"));
return securityInterceptor;
}
#Bean
SimplePasswordValidationCallbackHandler callbackHandler() {
SimplePasswordValidationCallbackHandler callbackHandler = new SimplePasswordValidationCallbackHandler();
callbackHandler.setUsersMap(Collections
.singletonMap("user", "password"));
return callbackHandler;
}
#Bean
PayloadLoggingInterceptor payloadLoggingInterceptor() {
return new PayloadLoggingInterceptor();
}
#Bean
PayloadValidatingInterceptor payloadValidatingInterceptor() {
final PayloadValidatingInterceptor payloadValidatingInterceptor = new PayloadValidatingInterceptor();
payloadValidatingInterceptor.setSchema(new ClassPathResource(
"devices.xsd"));
return payloadValidatingInterceptor;
}
#Override
public void addInterceptors(List<EndpointInterceptor> interceptors) {
interceptors.add(payloadLoggingInterceptor());
interceptors.add(payloadValidatingInterceptor());
interceptors.add(securityInterceptor());
}
}
Security policy:
<xwss:SecurityConfiguration xmlns:xwss="http://java.sun.com/xml/ns/xwss/config">
<xwss:UsernameToken digestPassword="false" useNonce="false" />
</xwss:SecurityConfiguration>
But now i want to replace this username and password authentication with a certificate. I prefere not to do this in xml, but rather implement this in my existing code as shown above.
We finaly figured this out some months ago, from what I remember our configuration looked like this.
add this to your web.xml
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
this needs to be present in your mvc-dispatcher-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:mvc="http://www.springframework.org/schema/mvc"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/web-services
http://www.springframework.org/schema/web-services/web-services-2.0.xsd">
<context:component-scan base-package="com.yourpackage" />
<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory" />
<bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<constructor-arg ref="messageFactory" />
<property name="defaultUri"
value="${backend.ip}devices" />
<property name="interceptors">
<list>
<ref local="xwsSecurityInterceptor" />
</list>
</property>
</bean>
<bean id="xwsSecurityInterceptor"
class="org.springframework.ws.soap.security.xwss.XwsSecurityInterceptor">
<property name="policyConfiguration" value="/WEB-INF/securityPolicy.xml" />
<property name="callbackHandlers">
<list>
<ref bean="keyStoreHandler" />
</list>
</property>
</bean>
<bean id="keyStore"
class="org.springframework.ws.soap.security.support.KeyStoreFactoryBean">
<property name="password" value="yourpassword" />
<property name="location" value="/WEB-INF/yourkeystore.jks" />
</bean>
<bean id="keyStoreHandler"
class="org.springframework.ws.soap.security.xwss.callback.KeyStoreCallbackHandler">
<property name="keyStore" ref="keyStore" />
<property name="privateKeyPassword" value="yourpassword" />
<property name="defaultAlias" value="client" />
</bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<!-- LOAD PROPERTIES -->
<context:property-placeholder
location="WEB-INF/config.properties"
ignore-unresolvable="true" />
<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:annotation-driven />
</beans>
The jks file is a java keystore file wich holds your certificate.
SecurityPolicy.xml
<xwss:SecurityConfiguration dumpMessages="true" xmlns:xwss="http://java.sun.com/xml/ns/xwss/config">
<xwss:Sign includeTimestamp="true">
<xwss:X509Token certificateAlias="yourcertificatealias" />
</xwss:Sign>
</xwss:SecurityConfiguration>
This is all done using the xws-security library from oracle, you need the following dependency for this.
<dependency>
<groupId>com.sun.xml.wss</groupId>
<artifactId>xws-security</artifactId>
<version>3.0</version>
<exclusions>
<exclusion>
<groupId>javax.xml.crypto</groupId>
<artifactId>xmldsig</artifactId>
</exclusion>
</exclusions>
</dependency>
We finnaly got this working after we found some good explanation about certificate authentication in this awesome book!
'Spring Web Services 2 Cookbook by Hamidreza Sattari'
If you have any further questions regarding this implementation then just ask away! :d

Memory leak , tomcat 7

When you start tomcat,
it consumes 70mbs of memory,
when I make requests then it consumes 80mbs,
never back to 70mbs
Crud code
package br.com.controlevendas.recurso;
import java.io.IOException;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import br.com.controlevendas.controle.ClienteControle;
import br.com.controlevendas.modelo.Cliente;
#Component
#Path("/cliente")
public class ClienteRecurso {
#Autowired
private ClienteControle clienteControle;
#GET
#Path("/lista")
#Produces(MediaType.APPLICATION_JSON)
public List<Cliente> listar() {
List<Cliente> clienteList = this.clienteControle.listar();
try {
this.clienteControle.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return clienteList;
}
#POST
#Path("")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Cliente inserir(Cliente cliente) {
cliente = this.clienteControle.salvar(cliente);
try {
this.clienteControle.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return cliente;
}
#PUT
#Path("")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Cliente alterar(Cliente cliente) {
cliente = this.clienteControle.alterar(cliente);
try {
this.clienteControle.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return cliente;
}
#GET
#Path("/{id}")
#Produces(MediaType.APPLICATION_JSON)
public Cliente buscar(#PathParam("id") Integer id) {
Cliente cliente = new Cliente();
cliente.setIdcliente(id);
cliente = this.clienteControle.buscar(cliente);
try {
this.clienteControle.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return cliente;
}
#DELETE
#Path("/{id}")
public void remover(#PathParam("id") Integer id) {
Cliente cliente = new Cliente();
cliente.setIdcliente(id);
cliente = this.clienteControle.remover(cliente);
try {
this.clienteControle.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
ClienteControle
package br.com.controlevendas.controle;
import java.io.Closeable;
import java.util.List;
import br.com.controlevendas.modelo.Cliente;
public interface ClienteControle extends Closeable {
Cliente salvar(Cliente cliente);
Cliente alterar(Cliente cliente);
Cliente remover(Cliente cliente);
Cliente buscar(Cliente cliente);
List<Cliente> listar();
}
ClienteControleImplementacao
package br.com.controlevendas.controle.implementacao;
import java.io.IOException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import br.com.controlevendas.controle.ClienteControle;
import br.com.controlevendas.dao.ClienteDAO;
import br.com.controlevendas.modelo.Cliente;
#Service
public class ClienteControleImplementacao implements ClienteControle {
#Autowired
private ClienteDAO clienteDAO;
#Override
public void close() throws IOException {
this.clienteDAO.close();
}
#Transactional(propagation = Propagation.REQUIRED)
#Override
public Cliente salvar(Cliente cliente) {
return this.clienteDAO.salvar(cliente);
}
#Transactional(propagation = Propagation.REQUIRED)
#Override
public Cliente alterar(Cliente cliente) {
return this.clienteDAO.alterar(cliente);
}
#Override
public Cliente buscar(Cliente cliente) {
return this.clienteDAO.buscar(cliente);
}
#Override
public List<Cliente> listar() {
return this.clienteDAO.listar();
}
#Transactional(propagation = Propagation.REQUIRED)
#Override
public Cliente remover(Cliente cliente) {
return this.clienteDAO.remover(cliente);
}
}
ClienteDAO
package br.com.controlevendas.dao;
import java.io.Closeable;
import java.util.List;
import br.com.controlevendas.modelo.Cliente;
public interface ClienteDAO extends Closeable {
Cliente salvar(Cliente cliente);
Cliente alterar(Cliente cliente);
Cliente remover(Cliente cliente);
Cliente buscar(Cliente cliente);
List<Cliente> listar();
}
ClienteDAOImplementacao
package br.com.controlevendas.dao.implementacao;
import java.io.IOException;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import br.com.controlevendas.dao.ClienteDAO;
import br.com.controlevendas.modelo.Cliente;
#Repository
public class ClienteDAOImplementacao implements ClienteDAO {
#PersistenceContext
private EntityManager entityManager;
#Override
public Cliente salvar(Cliente cliente) {
this.entityManager.persist(cliente);
return cliente;
}
#Override
public Cliente alterar(Cliente cliente) {
return this.entityManager.merge(cliente);
}
#Override
public Cliente buscar(Cliente cliente) {
Query query = this.entityManager.createQuery("from Cliente where idcliente = ?");
query.setParameter(1, cliente.getIdcliente());
return (Cliente) query.getSingleResult();
}
#SuppressWarnings("unchecked")
#Override
public List<Cliente> listar() {
Query query = this.entityManager.createQuery("from Cliente");
return query.getResultList();
}
#Override
public void close() throws IOException {
this.entityManager.close();
}
#Override
public Cliente remover(Cliente cliente) {
cliente = this.entityManager.getReference(Cliente.class, cliente.getIdcliente());
this.entityManager.remove(cliente);
return cliente;
}
}
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">
<persistence-unit name="controlevendas">
<!-- provedor/implementacao do JPA -->
<provider>org.hibernate.ejb.HibernatePersistence</provider>
</persistence-unit>
</persistence>
WebContent/META-INF/context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context reladable="true">
<Resource
name="jdbc/vendas"
auth="Container"
type="javax.sql.DataSource"
maxActive="100"
maxIdle="30"
maxWait="60"
username="root"
password="root"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/controlevendas"/>
</Context>
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:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-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">
<context:annotation-config />
<context:component-scan base-package="br.com.controlevendas.controle.implementacao" />
<context:component-scan base-package="br.com.controlevendas.dao.implementacao" />
<context:component-scan base-package="br.com.controlevendas.recurso" />
<!-- <bean id="dataSourceMySQL" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> -->
<!-- <property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost/controlevendas" />
<property name="user" value="root" />
<property name="password" value="root" />
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<property name="maxStatements" value="50" />
<property name="checkoutTimeout" value="3000" />
<property name="idleConnectionTestPeriod" value="3000" />
<property name="maxIdleTime" value="180" />
<property name="numHelperThreads" value="5" />
<property name="acquireIncrement" value="1" />
<property name="acquireRetryAttempts" value="5" /> -->
<!-- </bean> -->
<bean id="dataSource.jndi" class="org.springframework.jndi.JndiObjectFactoryBean" scope="singleton" lazy-init="true">
<property name="jndiName" value="java:comp/env/jdbc/vendas" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<!-- <property name="dataSource" ref="dataSourceMySQL" /> -->
<property name="dataSource" ref="dataSource.jndi" />
<property name="jpaVendorAdapter">
<bean
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="MYSQL" />
<property name="showSql" value="true" />
<property name="generateDdl" value="false" />
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">false</prop>
<prop key="hibernate.generate_statistics">true</prop>
<prop key="hibernate.cglib.use_reflection_optimizer">true</prop>
<prop key="hibernate.jdbc.use_streams_for_binary">true</prop>
<prop key="hibernate.temp.use_jdbc_metadata_defaults">false</prop>
<prop key="hibernate.jdbc.batch_size">0</prop>
<prop key="hibernate.connection.release_mode">after_transaction</prop>
<prop key="hibernate.jdbc.use_get_generated_keys">true</prop>
<prop key="hibernate.statement_cache.size">0</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
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_3_0.xsd" version="3.0">
<display-name>ControleVendas</display-name>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>jersey-spring</servlet-name>
<servlet-class>
com.sun.jersey.spi.spring.container.servlet.SpringServlet
</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>br.com.controlevendas.recurso</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-spring</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<resource-ref>
<description>DataSource Vendas</description>
<res-ref-name>jdbc/vendas</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
<session-config>
<session-timeout>1</session-timeout>
</session-config>
</web-app>
hibernate 4.3.8
spring 4.14
jersey 1.18
jackson 1.9.13
Someone help with any tips?

Categories

Resources