spring boot build a war file deploy into an external container, error:NoSuchBeanDefinitionException: No qualifying bean of type - spring-boot

Trying to build a war file that is both executable and deployable into an external container and I get this error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.jusfoun.test.service.TestService com.jusfoun.test.controller.TestController.testService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testServiceImpl': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.jusfoun.test.dao.TestMapper] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#javax.annotation.Resource(shareable=true, lookup=, name=, description=, authenticationType=CONTAINER, type=class java.lang.Object, mappedName=)}
It works when started up via java -jar test.war
Project:
pom.xml:
<project>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--Quartz setting -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
</dependency>
<!--junit setting -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<!-- datasource heroku -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP-java6</artifactId>
<exclusions>
<exclusion>
<artifactId>tools</artifactId>
<groupId>com.sun</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- aspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
<!-- Spring boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Provided (for embedded war support) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<!-- myBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- mybatis pagehelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>3.6.3</version>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.hateoas</groupId>
<artifactId>spring-hateoas</artifactId>
</dependency>
<!-- javax -->
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.53</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<classifier>jdk15</classifier>
<version>2.4</version>
</dependency>
<!-- other service dependency package of jusfoun -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<useSystemClassLoader>true</useSystemClassLoader>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
</plugins>
</build>
<packaging>war</packaging>
</project>
Application.java:
#Configuration
#ComponentScan({"com.jusfoun.test"})
#EnableAutoConfiguration
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(applicationClass, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(applicationClass);
}
private static Class<Application> applicationClass = Application.class;
}
TestController.java
package com.jusfoun.test.controller;
#RestController
#RequestMapping(value = "/test")
public class TestController {
#Autowired
private TestService testService;
/**
* GET /test -> show test
*/
#RequestMapping(value = "/get", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public String test() {
System.out.println("teststestestsetstsetest");
return testService.test();
}
}
TestService.java
package com.jusfoun.test.service;
public interface TestService {
String test();
}
TestServiceImpl.java
package com.jusfoun.test.service.impl;
#Service
public class TestServiceImpl implements TestService {
#Resource
private TestMapper testMapper;
#Override
public String test() {
List<Test> tlist = testMapper.selectByExample(null);
JSONArray array = JSONArray.fromObject(tlist);
return array.toString();
}
}
TestMapper.java
package com.jusfoun.test.dao;
#Component
public interface TestMapper {
...
}
TestMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.jusfoun.test.dao.TestMapper" >
...
MapperClassNamePlugin
package com.jusfoun.test.dao.mybatis.plugin;
import java.util.List;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
public class MapperClassNamePlugin extends PluginAdapter {
public boolean validate(List<String> warnings) {
return true;
}
#Override
public void initialized(IntrospectedTable table) {
super.initialized(table);
table.setMyBatis3JavaMapperType(table.getMyBatis3JavaMapperType()
.replaceAll("Mapper$", "Dao"));
}
}
MapperXmlNamePlugin
package com.jusfoun.test.dao.mybatis.plugin;
import java.util.List;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
public class MapperXmlNamePlugin extends PluginAdapter {
public boolean validate(List<String> warnings) {
return true;
}
#Override
public void initialized(IntrospectedTable table) {
super.initialized(table);
table.setMyBatis3JavaMapperType(table.getMyBatis3JavaMapperType()
.replaceAll("Mapper", ""));
}
}
DataBaseConfiguration.java
#Configuration
#EnableTransactionManagement
public class DataBaseConfiguration implements EnvironmentAware {
private RelaxedPropertyResolver propertyResolver;
private static Logger log = LoggerFactory
.getLogger(DataBaseConfiguration.class);
private Environment env;
#Override
public void setEnvironment(Environment env) {
this.env = env;
this.propertyResolver = new RelaxedPropertyResolver(env, "jdbc.");
}
#Bean(destroyMethod = "shutdown")
public DataSource dataSource() {
log.debug("Configruing DataSource");
if (propertyResolver.getProperty("url") == null
&& propertyResolver.getProperty("databaseName") == null) {
log.error("Your database conncetion pool configuration is incorrct ! The application "
+ "cannot start . Please check your jdbc");
Arrays.toString(env.getActiveProfiles());
throw new ApplicationContextException(
"DataBase connection pool is not configured correctly");
}
HikariConfig config = new HikariConfig();
config.setDataSourceClassName(propertyResolver
.getProperty("dataSourceClassName"));
if (propertyResolver.getProperty("url") == null
|| "".equals(propertyResolver.getProperty("url"))) {
config.addDataSourceProperty("databaseName",
propertyResolver.getProperty("databaseName"));
config.addDataSourceProperty("serverName",
propertyResolver.getProperty("serverName"));
} else {
config.addDataSourceProperty("url",
propertyResolver.getProperty("url"));
}
config.setUsername(propertyResolver.getProperty("username"));
config.setPassword(propertyResolver.getProperty("password"));
if ("com.mysql.jdbc.jdbc2.optional.MysqlDataSource"
.equals(propertyResolver.getProperty("dataSourceName"))) {
config.addDataSourceProperty("cachePrepStmts",
propertyResolver.getProperty("cachePrepStmts"));
config.addDataSourceProperty("prepStmtCacheSize",
propertyResolver.getProperty("prepStmtsCacheSize"));
config.addDataSourceProperty("prepStmtCacheSqlLimit",
propertyResolver.getProperty("prepStmtCacheSqlLimit"));
config.addDataSourceProperty("userServerPrepStmts",
propertyResolver.getProperty("userServerPrepStmts"));
}
return new HikariDataSource(config);
}
}
MybatisConfiguration.java
#Configuration
#ConditionalOnClass({ EnableTransactionManagement.class, EntityManager.class })
#AutoConfigureAfter({ DataBaseConfiguration.class })
#MapperScan(basePackages={"com.jusfoun.test.dao"})
public class MybatisConfiguration implements EnvironmentAware {
private static Log logger = LogFactory.getLog(MybatisConfiguration.class);
private RelaxedPropertyResolver propertyResolver;
#Inject
private DataSource dataSource;
#Override
public void setEnvironment(Environment environment) {
this.propertyResolver = new RelaxedPropertyResolver(environment,"mybatis.");
}
#Bean
#ConditionalOnMissingBean
public SqlSessionFactory sqlSessionFactory() {
try {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
sessionFactory.setTypeAliasesPackage(propertyResolver
.getProperty("typeAliasesPackage"));
sessionFactory
.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources(propertyResolver
.getProperty("mapperLocations")));
sessionFactory
.setConfigLocation(new DefaultResourceLoader()
.getResource(propertyResolver
.getProperty("configLocation")));
return sessionFactory.getObject();
} catch (Exception e) {
logger.warn("Could not confiure mybatis session factory");
return null;
}
}
#Bean
#ConditionalOnMissingBean
public DataSourceTransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource);
}
}

Using mybatis-spring-boot-starter (https://github.com/mybatis/spring-boot-starter), your setup can be simplified to the following:
Remove DataBaseConfiguration and MybatisConfiguration (which will be done by mybatis-spring-boot-starter.
Modifiy TestMapper:
package com.jusfoun.test.dao;
#Mapper
public interface TestMapper {
...
}

I remove annotation of #ConditionalOnClass in MybatisConfiguration.
The project works when war deploy into an external container(tomcat8).
Before remove the annotation, it works with java -jar xxx.war but not works deploy into external tomcat.
#Configuration
#AutoConfigureAfter({ DataBaseConfiguration.class })
#MapperScan(basePackages={"com.jusfoun.test.dao"})
public class MybatisConfiguration implements EnvironmentAware {

Related

Error creating bean with name 'dietaController'

So, I have a problem like this:
2020-01-30 22:54:20.059 ERROR 8040 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dietaController': Unsatisfied dependency expressed through field 'dietaRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dietaRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.diet4you.LapkoEkaterina.Entity.Dieta
My 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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.diet4you</groupId>
<artifactId>LapkoEkaterina</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
<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>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.3.2.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.3.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.16.Final</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
My Entity:
#Entity
#Table(name = "diety")
public class Dieta {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
#Column(name="DIETA_ID") private int dietaId;
#NotEmpty
#Column(unique=true, name ="DIETA_NAZWA")
private String nazwa;
#NotEmpty
#Column(name="OPIS") private String opis;
public Dieta(){ }
public Dieta (int dietaId,String nazwa, String opis )
{ this.dietaId = dietaId;
this.nazwa = nazwa;
this.opis = opis; }
public int getDietaId() {
return dietaId; }
public void setDietaId(int dietaId) {
this.dietaId = dietaId; }
public String getNazwa() {
return nazwa; }
public void setNazwa(String nazwa) {
this.nazwa = nazwa; }
public String getOpis() {
return opis; }
public void setOpis(String opis) {
this.opis = opis; }
}
My repository:
#Repository
public interface DietaRepository extends JpaRepository<Dieta, String> {
Dieta findByName (String name);
}
And my Controller:
#RestController
public class DietaController {
#Autowired
private DietaRepository dietaRepository;
#GetMapping("/dieta")
public List<Dieta> getAllNotes() {
return dietaRepository.findAll();
}
}
Application java class:
#Configuration
#SpringBootApplication
#EnableJpaRepositories
#EntityScan ( basePackages = { " com.diet4you.LapkoEkaterina" })
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
remove space here #EntityScan ( basePackages = { " com.diet4you.LapkoEkaterina" }) between " and com.diet4you...
change extends JpaRepository<Dieta, String> to extends JpaRepository<Dieta, Integer>
remove or fix Dieta findByName (String name) at repository interface, it's mistake

Parameter 0 of constructor in com.demo.service.NmpAppService required a bean named 'entityManagerFactory' that could not be found

I am trying to run a simple api flow in java spring and I am getting the following error:
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in com.nmp.bts.webapps.bsc.btbsc.service.NmpAppService required a bean named 'entityManagerFactory' that could not be found.
Action:
Consider defining a bean named 'entityManagerFactory' in your configuration.>
<Oct 25, 2019 10:37:51 AM EEST> <Notice> <Stdout> <BEA-000000> <WARN: The method class org.apache.commons.logging.impl.SLF4JLogFactory#release() was invoked.>
<Oct 25, 2019 10:37:51 AM EEST> <Notice> <Stdout> <BEA-000000> <WARN: Please see http://www.slf4j.org/codes.html#release for an explanation.>
<Oct 25, 2019 10:37:51 AM EEST> <Error> <Deployer> <BEA-149265> <Failure occurred in the execution of deployment request with ID "48455312047066616" for task "216" on [partition-name: DOMAIN]. Error is: "weblogic.application.ModuleException: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available"
weblogic.application.ModuleException: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
at weblogic.application.internal.ExtensibleModuleWrapper.start(ExtensibleModuleWrapper.java:140)
at weblogic.application.internal.flow.ModuleListenerInvoker.start(ModuleListenerInvoker.java:124)
at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:237)
at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:232)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:45)
Truncated. see log file for complete stacktrace
Caused By: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:687)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1207)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351)
Truncated. see log file for complete stacktrace
I want to mention that I`ve tried all kind of stuffs starting from the other similar topics on stackoverflow, to change dependency and nothing worked for me.
Controller class: NmpAppController.java
#RestController
#RequestMapping("/api")
public class NmpAppController {
private final NmpAppService nmpAppService;
#Autowired
public NmpAppController(NmpAppService nmpAppService) {
this.nmpAppService = nmpAppService;
}
#GetMapping("/nmp-apps")
public List<NmpApp> getAllNmps() {
try {
return nmpAppService.getAllNmpApps();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
Service class: NmpAppService.java
#Service
public class NmpAppService {
private final NmpAppRepository nmpAppRepository;
public NmpAppService(NmpAppRepository nmpAppRepository) {
this.nmpAppRepository = nmpAppRepository;
}
public NmpApp save(final NmpApp nmpApp) {
final NmpApp nmpAppToBeSaved = nmpApp;
NmpApp result = nmpAppRepository.saveAndFlush(nmpAppToBeSaved);
return result;
}
public NmpApp update(final NmpApp nmpApp) {
final NmpApp nmpAppitToBeSaved = nmpApp;
NmpApp result = nmpAppRepository.saveAndFlush(nmpAppToBeSaved);
return result;
}
public List<NmpApp> getAllNmpApps() {
return nmpAppRepository.findAll();
}
Repository class: NmpAppRepository.java
#Repository
public interface NmpAppRepository extends JpaRepository<NmpApp, Long> {
}
Domain class NmpApp.java
#Entity
#Table(name = "NMP_APP")
public class NmpApp {
#Id
#Column(name = "SEQ_NO")
private Long seqNo;
#Column(name = "HIST_DATE")
private Long histDate;
public NmpApp() {
}
public NmpApp(Long seqNo, Long histDate) {
this.seqNo = seqNo;
this.histDate = histDate;
}
public Long getSeqNo() {
return seqNo;
}
public void setSeqNo(Long seqNo) {
this.seqNo = seqNo;
}
public Long getHistDate() {
return histDate;
}
public void setHistDate(Long histDate) {
this.histDate = histDate;
}
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 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>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.nmp.bts.webapps.bsc</groupId>
<artifactId>nm-app</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>bt-bsc</name>
<description>BSC</description>
<packaging>war</packaging>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--<dependency>-->
<!--<groupId>org.springframework.boot</groupId>-->
<!--<artifactId>spring-boot-starter-data-jdbc</artifactId>-->
<!--</dependency>-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
<archive>
<manifest>
<addDefaultImplementationEntries>false</addDefaultImplementationEntries>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
</project>
Spring boot main class: Application.java
#EnableTransactionManagement
#SpringBootApplication(exclude = {HibernateJpaAutoConfiguration.class})
public class Application extends SpringBootServletInitializer implements WebApplicationInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(Application.class);
}
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
servletContext.getSessionCookieConfig().setHttpOnly(false);
super.onStartup(servletContext);
}
}
Later Edit: I uploaded the application.properties file
#Basic Spring Boot Config for Oracle
spring.datasource.url= jdbc:oracle:thin:#//:/
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
spring.datasource.jndi-name=jdbc/DEV_ADF_APPLDS
#hibernate config
spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect
spring.main.allow-bean-definition-overriding=true
I want to be able to perform simple CRUD operations on a database via swagger api caller (code shows only getAll but I do have the rest of code tho).
Usually happens when Spring is missing the spring-boot-starter-data-jpa since Spring infers the EntityManager from the Spring Data JPA which has an out of the box implementation for Hibernate ORM.
Adding the following to project pom.xml usually solves this problem
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
But in your case is available so the offending code is
spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect
Change to
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
Instead of spring-boot-starter-data-rest, try using the following
"org.springframework.boot:spring-boot-starter-data-jpa"
"org.springframework.boot:spring-boot-starter-jdbc"
Later edit: Also, don't forget to add #EnableTransactionManagement on the spring boot main class or on the database configuration class

Springboot app deployed in CloudFoundry - Get and Post operation on db fail

I am building a sample Spring application that will expose a REST
API to get and post data to a table in a database. Building the basic stuff.
I am using PostgreSQL for the data source in Cloud Foundry.
The GET API which returns a string works fine. The API which does POST returns 404 Not Found. The API which returns the entries in the table throws an exception.
Type Exception Report
Message Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.2.v20151217-774c696): org.eclipse.persistence.exceptions.DatabaseException
Description:
The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.2.v20151217-774c696): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.postgresql.util.PSQLException: ERROR: syntax error at or near "GROUP"
++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#Configuration
#EnableJpaRepositories(basePackageClasses =
CustomerFeedbackRepository.class)
#Profile("cloud")
public class CloudDatabaseConfig extends AbstractCloudConfig {
#Bean
public DataSource dataSource() {
List<String> dataSourceNames =
Arrays.asList("BasicDbcpPooledDataSourceCreator","TomcatJdbcPooledDataSourceCreator","HikariCpPooledDataSourceCreator","TomcatDbcpPooledDataSourceCreator");
DataSourceConfig dbConfig = new DataSourceConfig(dataSourceNames);
return connectionFactory().dataSource(dbConfig);
}
#Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
return EntityManagerFactoryProvider.get(dataSource, CustomerFeedback.class.getPackage().getName());
}
#Bean(name = "transactionManager")
public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
#PostMapping("/capturecf")
#RequestMapping(value ="CustomerFeedback", method = RequestMethod.POST)
public CustomerFeedback addFeedback(#RequestBody CustomerFeedback custfeedback)
{
return customerfeedbackrepo.save(custfeedback);
}
#PostMapping("/captureua")
#RequestMapping(value = "UsageActivity", method = RequestMethod.POST)
public UsageActivity addUsageTracking(#Valid #RequestBody UsageActivity usageActivity)
{
return usageactivityrepository.save(usageActivity);
}
#GetMapping("/usageactivity")
public List<UsageActivity> getAllNotes() {
return usageactivityrepository.findAll();`enter code here`
}
<dependencies>
<!-- APIs for servlets and injection -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<!-- Spring Framework and Spring WebMVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Logging library -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>com.sap.hcp.cf.logging</groupId>
<artifactId>cf-java-logging-support-logback</artifactId>
<version>${sap.logging.version}</version>
</dependency>
<dependency>
<groupId>com.sap.hcp.cf.logging</groupId>
<artifactId>cf-java-logging-support-servlet</artifactId>
<version>${sap.logging.version}</version>
</dependency>
<!-- JSON conversion -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.1</version>
</dependency>
<!-- Actuator for adding management endpoints -->
<dependency>
<groupId> org.springframework.boot</groupId>
<artifactId>spring-boot-actuator</artifactId>
<version>1.2.5.RELEASE</version>
</dependency>
<!-- Bean validation (#NotNull etc.) -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.1.Final</version>
</dependency>
<!-- MethodValidationPostProcessor relies on Expression Language -->
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>3.0.1-b04</version>
</dependency>
<!-- Spring Cloud Connector -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-spring-service-connector</artifactId>
<version>1.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-cloudfoundry-connector</artifactId>
<version>1.2.1.RELEASE</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.9.2.RELEASE</version>
<exclusions>
<exclusion>
<!-- We need spring-core 4.2 or later, but spring-data includes 4.1.9 -->
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- EclipseLink as JPA implementation -->
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa</artifactId>
<version>2.6.2</version>
</dependency>
<!-- PostgreSQL database implementations -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4-1206-jdbc41</version>
<scope>runtime</scope>
</dependency>
<!-- connection pooling -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.1.1</version>
<scope>runtime</scope>
</dependency>
<!-- Testing -->
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<!-- Use MockMvcResultMatchers.jsonPath to assert the JSON body -->
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.2.0</version>
<scope>test</scope>
</dependency>
<!-- H2 (in-memory) database implementation -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.184</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>customerconnect</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<!-- Provides the application at http://localhost:8080/ using an embedded
Tomcat server with a pre-configured environment referencing the SAP proxy -->
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<port>${maven.tomcat.port}</port>
<path>/</path>
<systemProperties>
<http.proxyHost>${http.proxyHost}</http.proxyHost>
<http.proxyPort>${http.proxyPort}</http.proxyPort>
</systemProperties>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>findbugs-maven-plugin</artifactId>
<version>3.0.2</version>
<executions>
<execution>
<phase>verify</phase>
<goals>
<goal>findbugs</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-pmd-plugin</artifactId>
<version>3.5</version>
<executions>
<execution>
<phase>verify</phase>
<goals>
<goal>pmd</goal>
<goal>cpd</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.5.201505241946</version>
<executions>
<execution>
<id>default-prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>default-report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
<execution>
<id>default-check</id>
<goals>
<goal>check</goal>
</goals>
<configuration>
<rules>
</rules>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jxr-plugin</artifactId>
<version>2.5</version>
</plugin>
</plugins>
</reporting>
</project>
package com.sap.customerconnect.ads.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import com.sap.customerconnect.ads.models.UsageActivity;
import com.sap.customerconnect.ads.models.UsageActivityPK;
#Component
#Repository
public interface UsageActivityRepository extends JpaRepository<UsageActivity, UsageActivityPK> {
}
package com.sap.customerconnect.ads.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import com.sap.customerconnect.ads.models.CustomerFeedback;
import com.sap.customerconnect.ads.models.CustomerFeedbackPK;
#Component
#Repository
public interface CustomerFeedbackRepository extends JpaRepository<CustomerFeedback, CustomerFeedbackPK>{
}
package com.sap.customerconnect.ads.models;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.Table;
#IdClass(UsageActivityPK.class)
#Entity
#Table(name = "UsageActivity")
public class UsageActivity {
#Id
#Column(name = "PRODUCT_ID")
private String ProductId;
#Id
#Column(name = "CUSTOMER_ID")
private String CustomerId;
#Id
#Column(name = "SCREEN_ID")
private String ScreenId;
#Column(name = "GROUP")
private String Group;
#Column(name = "ACTION")
private String Action;
#Column(name = "DESCRIPTION")
private String Description;
#Column(name = "COUNT")
private Integer Count;
public UsageActivity() {
}
public String getProductId() {
return ProductId;
}
public void setProductId(String productId) {
ProductId = productId;
}
public String getCustomerId() {
return CustomerId;
}
public void setCustomerId(String customerId) {
CustomerId = customerId;
}
public String getScreenId() {
return ScreenId;
}
public void setScreenId(String screenId) {
ScreenId = screenId;
}
public String getGroup() {
return Group;
}
public void setGroup(String group) {
Group = group;
}
public String getAction() {
return Action;
}
public void setAction(String action) {
Action = action;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
public Integer getCount() {
return Count;
}
public void setCount(Integer count) {
Count = count;
}
public UsageActivity(String productId, String customerId, String screenId, String group, String action,
String description, Integer count) {
super();
ProductId = productId;
CustomerId = customerId;
ScreenId = screenId;
Group = group;
Action = action;
Description = description;
Count = count;
}
}
package com.sap.customerconnect.ads.models;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Embeddable;
#Embeddable
public class UsageActivityPK implements Serializable{
private static final long serialVersionUID = 1L;
#Column(name = "PRODUCT_ID")
private String ProductId;
#Column(name = "CUSTOMER_ID")
private String CustomerId;
#Column(name = "SCREEN_ID")
private String ScreenId;
}
The POST and GET operations on the repository does not work.

Spring Boot Failure due to Transaction Management

I am currently developing an application using spring boot with cassandra as the database.
I have written a class which initializes my cassandra cluster. The problem starts as soon as I start using #Transactional in my DAO Layer Query Methods. System doesn't allow me to use them at a below error message is thrown at runtime -
An exception has occured in method getMdoBean with msg: No qualifying bean of type 'org.springframework.transaction.PlatformTransactionManager' available.
I don't understand what is going wrong. My app works fine without spring boot with no issues related to Transaction Management.
I tried adding JPA Support along with H2 Database and it resolved my problem. I did my homework and read about H2 Database and its in-memory data storage mechanism. I am failing to understand how is TransactionManagement issue is getting fixed? Is it because of H2 Database drivers which are taking care of it?
Secondly, I don't need H2 Database hence this solution does not seems to be good for me. Backend is Cassandra for my application. Any leads would be helpful. Thanks!
POM
<?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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.shc.sov</groupId>
<artifactId>SOV</artifactId>
<version>4.4.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>SOV</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.3.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<org.springframework.version>4.1.4.RELEASE</org.springframework.version>
<jersey.version>1.14</jersey.version>
<maven.antrun.plugin.version>1.8</maven.antrun.plugin.version>
<java.version>1.8</java.version>
</properties>
<repositories>
<repository>
<id>shc-central</id>
<name>Sears Libraries</name>
<url>http://obuartifactoryvip.prod.ch3.s.com/artifactory/libs-release</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>shc-snapshots</id>
<name>Sears Snapshot Libraries</name>
<url>http://obuartifactoryvip.prod.ch3.s.com/artifactory/libs-snapshot</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<build>
<finalName>dpsserver</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>prod/*.*</exclude>
<exclude>qa/*.*</exclude>
<exclude>stress/*.*</exclude>
<exclude>dev/*.*</exclude>
<exclude>dev-spring-boot</exclude>
</excludes>
<filtering>false</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<id>config</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<descriptor>config.xml</descriptor>
<attach>true</attach>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
<configuration>
<!-- Always download and attach dependencies source code -->
<downloadSources>true</downloadSources>
<downloadJavadocs>false</downloadJavadocs>
<!-- Avoid type mvn eclipse:eclipse -Dwtpversion=2.0 -->
<wtpversion>2.0</wtpversion>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifestEntries>
<Class-Path>config/</Class-Path>
</manifestEntries>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.4.3.RELEASE</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<!-- Core utilities used by other modules. Define this if you use Spring
Utility APIs (org.springframework.core.*/org.springframework.util.*) -->
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency> -->
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- In memory database used by spring-boot -->
<!-- <dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency> -->
<dependency>
<groupId>com.searshc.dce.persistence</groupId>
<artifactId>DcePersistence</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>${jersey.version}</version>
<exclusions>
<exclusion>
<artifactId>jaxb-impl</artifactId>
<groupId>com.sun.xml.bind</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>${jersey.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<!-- <dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency> -->
<!-- https://mvnrepository.com/artifact/log4j/apache-log4j-extras -->
<dependency>
<groupId>log4j</groupId>
<artifactId>apache-log4j-extras</artifactId>
<version>1.2.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<!-- <dependency> <groupId>javax.ws.rs</groupId> <artifactId>jsr311-api</artifactId>
<version>1.1.1</version> </dependency> -->
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-spring</artifactId>
<version>${jersey.version}</version>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
</exclusion>
<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>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</exclusion>
<exclusion>
<artifactId>spring-aop</artifactId>
<groupId>org.springframework</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.2.7-b41</version>
</dependency>
<!-- <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId>
<version>2.5</version> <scope>provided</scope> </dependency> -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>1.7.2</version>
</dependency>
<!-- Unit test level dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.5</version>
<scope>test</scope>
</dependency>
<!-- <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-all</artifactId>
<version>1.9.5</version> <scope>test</scope> </dependency> -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-cassandra</artifactId>
<version>1.4.6.RELEASE</version>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Compilation Level Dependencies -->
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>${maven.antrun.plugin.version}</version>
<scope>compile</scope>
</dependency>
<!-- DATASTAX -->
<dependency>
<groupId>com.datastax.cassandra</groupId>
<artifactId>cassandra-driver-core</artifactId>
<version>2.1.4</version>
</dependency>
<!-- DATASTAX -->
</dependencies>
</project>
Cassandra Configuration Class
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.cassandra.config.CassandraClusterFactoryBean;
import org.springframework.data.cassandra.config.CassandraSessionFactoryBean;
import org.springframework.data.cassandra.config.SchemaAction;
import org.springframework.data.cassandra.convert.CassandraConverter;
import org.springframework.data.cassandra.convert.MappingCassandraConverter;
import org.springframework.data.cassandra.core.CassandraOperations;
import org.springframework.data.cassandra.core.CassandraTemplate;
import org.springframework.data.cassandra.mapping.BasicCassandraMappingContext;
import org.springframework.data.cassandra.mapping.CassandraMappingContext;
import org.springframework.data.cassandra.repository.config.EnableCassandraRepositories;
import com.datastax.driver.core.PlainTextAuthProvider;
#Configuration
#ImportResource("application-context.xml")
#PropertySource(value = { "classpath:cassandra.properties" })
#EnableCassandraRepositories(basePackages = {"com.spring.sample"})
public class CassandraDsConfig {
#Autowired
private Environment env;
#Bean
public CassandraClusterFactoryBean configureCassandraCluster() {
CassandraClusterFactoryBean clusterFactory = new CassandraClusterFactoryBean();
clusterFactory.setContactPoints(env.getProperty("cassandra.Newcontactpoints"));
clusterFactory.setPort(Integer.parseInt(env.getProperty("cassandra.Newport")));
PlainTextAuthProvider plainTextAuthProvider = new PlainTextAuthProvider(env.getProperty("cassandra.username"),
env.getProperty("cassandra.password"));
clusterFactory.setAuthProvider(plainTextAuthProvider);
return clusterFactory;
}
#Bean
public CassandraMappingContext mappingContext() {
return new BasicCassandraMappingContext();
}
#Bean
public CassandraConverter converter() {
return new MappingCassandraConverter(mappingContext());
}
#Bean
public CassandraSessionFactoryBean session() throws Exception {
CassandraSessionFactoryBean session = new CassandraSessionFactoryBean();
session.setCluster(configureCassandraCluster().getObject());
session.setKeyspaceName(env.getProperty("cassandra.Newkeyspace"));
session.setConverter(converter());
session.setSchemaAction(SchemaAction.NONE);
return session;
}
#Primary
#Bean("cassandraNewTemplate")
public CassandraOperations cassandraNewTemplate() throws Exception {
return new CassandraTemplate(session().getObject());
}
}
Spring Boot Main Class
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.PropertySource;
//import org.springframework.context.annotation.PropertySource;
import org.springframework.boot.Banner;
/**
* #author bnarula
*
*/
#SpringBootApplication
#ImportResource("application-context.xml")
#Import(CassandraDsConfig.class)
#PropertySource("dps.properties")
#EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
#ComponentScan(basePackages = "com.shc.marketplace.ias")
public class DPSMainModule extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return configureApplication(builder);
}
public static void main(String[] args) {
configureApplication(new SpringApplicationBuilder()).run(args);
}
private static SpringApplicationBuilder configureApplication(SpringApplicationBuilder builder) {
return builder.sources(DPSMainModule.class).bannerMode(Banner.Mode.OFF);
}
}
DAO Layer Class for Caching -
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.cassandra.core.CassandraOperations;
import org.springframework.transaction.annotation.Transactional;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.datastax.driver.core.querybuilder.Select;
import com.searshc.dce.persistence.DcePersistence.dao.beans.FreightAreaBean;
import com.searshc.dce.persistence.DcePersistence.dao.beans.FreightAreaPOJO;
import com.shc.scinventory.dps.server.dao.CacheBuilderDAO;
import com.shc.scinventory.dps.server.model.StoretoRRCPOJO;
import com.shc.scinventory.dps.server.model.ZiptoWarehousePOJO;
public class CacheBuilderDAOImpl implements CacheBuilderDAO {
private static Logger logger = Logger.getLogger(CacheBuilderDAOImpl.class);
private Map<String, String> storeToRRCMap = new HashMap<String, String>();
private Map<String, String> ziptoWarehouseMap = new HashMap<String, String>();
private Map<String, List<FreightAreaBean>> zipToFaMap = new HashMap<String, List<FreightAreaBean>>();
List<StoretoRRCPOJO> storeToRRCList = new ArrayList<StoretoRRCPOJO>();
public List<StoretoRRCPOJO> getStoreToRRCList() {
return storeToRRCList;
}
public void setStoreToRRCList(List<StoretoRRCPOJO> storeToRRCList) {
this.storeToRRCList = storeToRRCList;
for (StoretoRRCPOJO storetoRRCBean : storeToRRCList) {
storeToRRCMap.put(storetoRRCBean.getStore(), storetoRRCBean.getRrc());
}
}
#Autowired
private CassandraOperations cassandraOperations;
private String keyspace;
#Override
public void initStatements() {
logger.debug("CacheBuilderDAOImpl : Inside method init");
if (cassandraOperations == null) {
logger.error("Cassandra not available");
} else {
List<ZiptoWarehousePOJO> ziptoWarehouseList = getZiptoWarehouseMapping();
List<StoretoRRCPOJO> storetoRRCList = getStoretoRRCMapping();
for (ZiptoWarehousePOJO ziptoWarehouseBean : ziptoWarehouseList) {
ziptoWarehouseMap.put(ziptoWarehouseBean.getDestinationZip(), ziptoWarehouseBean.getDcUnit());
}
setStoreToRRCList(storetoRRCList);
refreshZipToFaMapping();
}
}
public void refreshZipToFaMapping() {
zipToFaMap = getZipToFAMapping();
}
#Transactional
public Map<String, List<FreightAreaBean>> getZipToFAMapping() {
logger.debug("Inside method getZipToFAMapping");
Map<String, List<FreightAreaBean>> result = new HashMap<String, List<FreightAreaBean>>();
try {
Select select = QueryBuilder.select().all().from("capacity", "freight_area");
List<FreightAreaPOJO> queryResult = cassandraOperations.select(select, FreightAreaPOJO.class);
for(FreightAreaPOJO faPOJO : queryResult) {
String zip = faPOJO.getGeocode_no();
if(!result.containsKey(zip)) {
result.put(zip, new LinkedList<FreightAreaBean>());
}
FreightAreaBean faBean = new FreightAreaBean();
BeanUtils.copyProperties(faPOJO, faBean);
result.get(zip).add(faBean);
}
} catch (Exception e) {
logger.error("getZipToFAMapping Error while fetch data from DB: " + e.getMessage());
e.printStackTrace();
}
logger.debug("Exiting method getZipToFAMapping");
return result;
}
public List<ZiptoWarehousePOJO> getZiptoWarehouseMapping() {
logger.debug("Inside method getZiptoWarehouseMapping");
List<ZiptoWarehousePOJO> result = null;
try {
Select select = QueryBuilder.select().all().from(getKeyspace(), "ziptowarehouse");
result = cassandraOperations.select(select, ZiptoWarehousePOJO.class);
} catch (Exception e) {
logger.error("getZiptoWarehouseMapping Error while fetch data from DB: " + e.getMessage());
}
logger.debug("Exiting method getZiptoWarehouseMapping");
return result;
}
public List<StoretoRRCPOJO> getStoretoRRCMapping() {
logger.debug("Inside method getStoretoRRCMapping");
List<StoretoRRCPOJO> result = null;
try {
Select select = QueryBuilder.select().all().from(getKeyspace(), "storetorrc");
result = cassandraOperations.select(select, StoretoRRCPOJO.class);
} catch (Exception e) {
logger.error("getStoretoRRCMapping Error while fetch data from DB: " + e.getMessage());
}
logger.debug("Exiting method getStoretoRRCMapping");
return result;
}
public String getKeyspace() {
return keyspace;
}
public void setKeyspace(String keyspace) {
this.keyspace = keyspace;
}
public Map<String, String> getStoreToRRCMap() {
return storeToRRCMap;
}
public void setStoreToRRCMap(Map<String, String> storeToRRCMap) {
this.storeToRRCMap = storeToRRCMap;
}
public Map<String, String> getZipToWarehouseMap() {
return ziptoWarehouseMap;
}
public void setZiptoWarehouseMap(Map<String, String> ziptoWarehouseMap) {
this.ziptoWarehouseMap = ziptoWarehouseMap;
}
public Map<String, List<FreightAreaBean>> getZipToFaMap() {
return zipToFaMap;
}
public void setZipToFaMap(Map<String, List<FreightAreaBean>> zipToFaMap) {
this.zipToFaMap = zipToFaMap;
}
}
If I use #Transactional in the above class at method level, it doesn't allow without adding H2 Support for JPA. It works fine after putting up below lines of code in POM.
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
I guess the reason is you excluded HibernateJpaAutoConfiguration, is there any reason to do so, otherwise I will suggest you to add it back, maybe also add #EnableTransactionManagement to your config class.

How to configure Spring Security + OAuth2

I'm building a REST Application using Spring Security + OAuth2.
If i use
curl -u clientapp:123456 -X POST http://localhost:8080/oauth/token -H "Accept:application/json" -d "username=admin&password=123456&grant_type=password"
I do not get the response
But if i add the application contextpath i am able to.
curl -u clientapp:123456 -X POST http://localhost:8080/demoproject/oauth/token -H "Accept:application/json" -d "username=admin&password=123456&grant_type=password"
Also getting success response
{"access_token":"dc86814f-94a5-43b7-9e8d-73b143b28c64","token_type":"bearer","re
fresh_token":"09c7e31e-b8e7-4bf2-a839-9e8d4702b822","expires_in":2837,"scope":"r
ead write"}
But when use the access token to request a secured API, I'm getting login page as response because of Spring Security Configuration.
Here is my Configration:
WebMvcInitializer.java
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class WebMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] {
WebConfig.class,
WebSecurityConfiguration.class,
Oauth2ServerConfiguration.AuthConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
WebSecurityConfiguration .java
#Configuration
#EnableWebSecurity
#EnableWebMvcSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("admin").password("123456").roles("USER", "ADMIN");
}
#Override
#Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Bean
public PasswordEncoder passwordEncoder() {
PasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().hasRole("USER");
//super.configure(http);
}
}
WebConfig.java
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "edu.demo.springoauth")
public class WebConfig extends WebMvcConfigurerAdapter {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("/static/");
}
}
SecurityInitializer.java
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer {
}
Oauth2ServerConfiguration.java
#Configuration
public class Oauth2ServerConfiguration {
private static final String SERVER_RESOURCE_ID = "oauthdemo";
private static InMemoryTokenStore tokenStore = new InMemoryTokenStore();
#Configuration
#EnableResourceServer
protected static class ResourceServer extends ResourceServerConfigurerAdapter {
#Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId(SERVER_RESOURCE_ID);
}
#Override
#Order(Ordered.HIGHEST_PRECEDENCE)
public void configure(HttpSecurity http) throws Exception {
http.requestMatchers().antMatchers("/oauth/**" , "/noauth/**" , "/api/r/**")
.and()
.authorizeRequests().antMatchers("/api/w/**").hasAuthority("ROLE_USER");
}
}
#Configuration
#EnableAuthorizationServer
protected static class AuthConfig extends AuthorizationServerConfigurerAdapter {
#Autowired
#Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
#Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.allowFormAuthenticationForClients();
}
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory().withClient("clientapp").authorizedGrantTypes("password","client_credentials", "authorization_code", "refresh_token", "implicit")
.authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT", "ROLE_USER")
.scopes("read", "write").resourceIds(SERVER_RESOURCE_ID).secret("123456").accessTokenValiditySeconds(3600);
}
#Bean
#Primary
public DefaultTokenServices tokenServices() {
DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setSupportRefreshToken(true);
tokenServices.setTokenStore(tokenStore);
return tokenServices;
}
}
}
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>edu.demo</groupId>
<artifactId>springoauth</artifactId>
<name>springoauth</name>
<packaging>war</packaging>
<version>1.0.0-BUILD-SNAPSHOT</version>
<properties>
<build.profile.id>dev</build.profile.id>
<java-version>1.8</java-version>
<spring.security.oauth2.version>2.0.1.RELEASE</spring.security.oauth2.version>
<spring-security.version>3.2.4.RELEASE</spring-security.version>
<spring.version>4.0.5.RELEASE</spring.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>${spring.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</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.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring-security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>${spring-security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring-security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>${spring.security.oauth2.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-dbcp</artifactId>
<version>7.0.47</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.1.8.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.22</version>
</dependency>
</dependencies>
<profiles>
<profile>
<id>dev</id>
<properties>
<build.profile.id>dev</build.profile.id>
</properties>
</profile>
</profiles>
<build>
<finalName>springoauth</finalName>
<filters>
<filter>profiles/${build.profile.id}/config.properties</filter>
</filters>
<resources>
<resource>
<filtering>true</filtering>
<directory>src/main/resources</directory>
<excludes>
<exclude>**/messages*.properties</exclude>
</excludes>
</resource>
<resource>
<filtering>false</filtering>
<directory>src/main/resources</directory>
<includes>
<include>**/messages*.properties</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.9</version>
<configuration>
<additionalProjectnatures>
<projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
</additionalProjectnatures>
<additionalBuildcommands>
<buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
</additionalBuildcommands>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>${java-version}</source>
<target>${java-version}</target>
<compilerArgument>-Xlint:all</compilerArgument>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<configuration>
<mainClass>org.test.int1.Main</mainClass>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
Is there something in spring configuration that I'm doing wrong?

Resources