Spring Boot + Tomcat + EclipseLink causes: Cannot apply class transformer without LoadTimeWeaver specified - spring

I'm currently struggleing around with a Spring-Boot application that should use EclipseLink as JPa implementation and that app should run within a Tomcat 8 container. Unfortunatelly I'm not able to get it to work.
As far as I read I need to add the spring-instruments.jar as java command line argument (javaagent), but I read somewhere that tomcat 8 is not requiring that because it automatically decides which load time weaver it uses. Does anyone have an idea what's going wrong here?
Basically I get the following exception when I try to run the application:
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.persistence.EntityManagerFactory]: Factory method 'entityManagerFactory' threw exception; nested exception is java.lang.IllegalStateException: Cannot apply class transformer without LoadTimeWeaver specified
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
... 95 more
Caused by: java.lang.IllegalStateException: Cannot apply class transformer without LoadTimeWeaver specified
at org.springframework.orm.jpa.persistenceunit.SpringPersistenceUnitInfo.addTransformer(SpringPersistenceUnitInfo.java:80)
at org.eclipse.persistence.jpa.PersistenceProvider.createContainerEntityManagerFactoryImpl(PersistenceProvider.java:373)
at org.eclipse.persistence.jpa.PersistenceProvider.createContainerEntityManagerFactory(PersistenceProvider.java:313)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:343)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:319)
at foo.AppConfiguration.entityManagerFactory(AppConfiguration.java:57)
at foo.AppConfiguration$$EnhancerBySpringCGLIB$$a92e9feb.CGLIB$entityManagerFactory$1(<generated>)
at foo.AppConfiguration$$EnhancerBySpringCGLIB$$a92e9feb$$FastClassBySpringCGLIB$$e4dbaad1.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:356)
at foo.AppConfiguration$$EnhancerBySpringCGLIB$$a92e9feb.entityManagerFactory(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
My pom.xml looks like:
<?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.ss.stock</groupId>
<artifactId>SimpleTest</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<url>http://raspberrypi:8080/manager/text</url>
<server>TomcatServer</server>
<path>/StockBatch</path>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.4.0.RELEASE</version>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
<version>1.4.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.6.3</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.3.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.10.2.RELEASE</version>
</dependency>
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901.jdbc4</version>
</dependency>
</dependencies>
</project>
And my Spring boot Configuration looks like:
#Configuration
#EnableJpaRepositories("foo")
#EnableTransactionManagement
#EnableLoadTimeWeaving
#EnableScheduling
public class AppConfiguration {
#Bean
public DataSource dataSource() {
DriverManagerDataSource dmds = new DriverManagerDataSource();
dmds.setUrl("jdbc:postgresql://raspberrypi:5432/stocks");
dmds.setUsername("abc");
dmds.setPassword("***");
dmds.setDriverClassName("org.postgresql.Driver");
return dmds;
}
#Bean
public EntityManagerFactory entityManagerFactory() {
EclipseLinkJpaVendorAdapter vendorAdapter = new EclipseLinkJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
vendorAdapter.setShowSql(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("foo");
factory.setDataSource(dataSource());
factory.getJpaPropertyMap().put("eclipselink.jdbc.batch-writing", "JDBC");
factory.getJpaPropertyMap().put("eclipselink.jdbc.batch-writing.size", "500");
factory.getJpaPropertyMap().put("eclipselink.persistence-context.flush-mode", "commit");
factory.afterPropertiesSet();
return factory.getObject();
}
#Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory());
return txManager;
}
}

Related

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityInterceptor' defined in class path resource

I need to sign using SOAP request and due to that, I need to use ws-security dep from Spring.
#ComponentScan(basePackages = {"mk.softnet.wsdl","mk.softnet.Porting"})
public class SoapConfig extends WsConfigurerAdapter {
#Bean
public XwsSecurityInterceptor securityInterceptor() {
XwsSecurityInterceptor securityInterceptor = new XwsSecurityInterceptor();
securityInterceptor.setPolicyConfiguration(new ClassPathResource("securityPolicy.xml"));
securityInterceptor.setCallbackHandler(callbackHandler());
//Security Policy -> securityPolicy.xml
return securityInterceptor;
}
#Bean
SimplePasswordValidationCallbackHandler callbackHandler() {
SimplePasswordValidationCallbackHandler callbackHandler = new SimplePasswordValidationCallbackHandler();
// TODO #rap: Use real username and passwords
callbackHandler.setUsersMap(Collections.singletonMap("user", "password"));
return callbackHandler;
}
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>2.1.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>mk.softnet</groupId>
<artifactId>Porting</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Porting</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>2.1.9.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-web-services</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-security</artifactId>
<version>2.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<version>5.1.2.RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.jvnet.jaxb2.maven2</groupId>
<artifactId>maven-jaxb2-plugin</artifactId>
<version>0.14.0</version>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<configuration>
<schemaLanguage>WSDL</schemaLanguage>
<generatePackage>mk.softnet.wsdl</generatePackage>
<schemas>
<schema>
<url>WDSL_URL
</url>
</schema>
</schemas>
</configuration>
</plugin>
</plugins>
</build>
</project>
Test set: mk.softnet.Porting.PortingApplicationTests
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 4.79 s <<< FAILURE! - in mk.softnet.Porting.PortingApplicationTests
contextLoads(mk.softnet.Porting.PortingApplicationTests) Time elapsed: 0.001 s <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityInterceptor' defined in class path resource [mk/softnet/Porting/config/SoapConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.ws.soap.security.xwss.XwsSecurityInterceptor]: Factory method 'securityInterceptor' threw exception; nested exception is java.lang.NoClassDefFoundError: com/sun/xml/wss/XWSSecurityException
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.ws.soap.security.xwss.XwsSecurityInterceptor]: Factory method 'securityInterceptor' threw exception; nested exception is java.lang.NoClassDefFoundError: com/sun/xml/wss/XWSSecurityException
Caused by: java.lang.NoClassDefFoundError: com/sun/xml/wss/XWSSecurityException
Caused by: java.lang.ClassNotFoundException: com.sun.xml.wss.XWSSecurityException
I tried to change version but did not get any success.
You need to add com.sun.xml.wss dependency.
Add this dependency to the pom.xml :
<dependency>
<groupId>com.sun.xml.wss</groupId>
<artifactId>xws-security</artifactId>
<version>3.0</version>
<scope>compile</scope>
<exclusions>
<exclusion>
<artifactId>xmldsig</artifactId>
<groupId>javax.xml.crypto</groupId>
</exclusion>
</exclusions>
<optional>true</optional>
</dependency>
Look at the pom for spring-ws-security - 2.2.0 RELEASE

Issue with Spring ServletRegistrationBean on official example

There are the following lines in the example of Spring-ws spring guide
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext);
servlet.setTransformWsdlLocations(true);
ServletRegistrationBean bean = new ServletRegistrationBean();
return new ServletRegistrationBean(servlet, "/ws/*");
I get the following error
The constructor ServletRegistrationBean(MessageDispatcherServlet, String) is undefined
How can I fix this error?. What version of Spring boot I have to use?
****EDITED
This is the pom.xml. I think it's the same than the guide. I work with Eclipse.
<?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.springframework</groupId>
<artifactId>gs-producing-web-service</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- tag::springws[] -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>wsdl4j</groupId>
<artifactId>wsdl4j</artifactId>
</dependency>
<!-- end::springws[] -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- tag::xsd[] -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>1.6</version>
<executions>
<execution>
<id>xjc</id>
<goals>
<goal>xjc</goal>
</goals>
</execution>
</executions>
<configuration>
<schemaDirectory>${project.basedir}/src/main/resources/</schemaDirectory>
<outputDirectory>${project.basedir}/src/main/java</outputDirectory>
<clearOutputDir>false</clearOutputDir>
</configuration>
</plugin>
<!-- end::xsd[] -->
</plugins>
</build>
</project>
Java class
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.ws.config.annotation.EnableWs;
import org.springframework.ws.config.annotation.WsConfigurerAdapter;
import org.springframework.ws.transport.http.MessageDispatcherServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
#EnableWs
#Configuration
public class WebServiceConfig extends WsConfigurerAdapter{
public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) {
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext);
servlet.setTransformWsdlLocations(true);
ServletRegistrationBean bean = new ServletRegistrationBean();
return new ServletRegistrationBean(servlet, "/ws/*");
}
Do I have to add dependencies to the pom.xml. What is the dependency wher is ServletRegistrationBean(servlet, "/ws/*");
The MetricsServlet needs to implement javax.servlet.Servlet dependency. You need to have this class in your project/classpath. To do this, declare this maven dependency:
<!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>

ClassNotFoundException CrudRepository

I'm reading the JPA docs on spring, and i'm trying to restructure my code.
What i have now:
BrewerRepository
#Repository
public class BrewerRepository {
#PersistenceContext(name = "vivesPU")
private EntityManager entityManager;
public List<Brewer> getAll() {
return null;
}
}
BrewerService
#Service
public class BrewerService {
#Autowired
private BrewerRepository brewerRepository;
public List<Brewer> getAll() {
return null;
}
}
HomeController
#Controller
public class HomeController {
#Autowired
private BrewerService brewerService;
#GetMapping("/")
public String index(Model model) {
List<Brewer> brewers = this.brewerService.getAll();
model.addAttribute("brewers", brewers);
return "index";
}
}
PersistenceJPAConfig
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories
public class PersistenceJPAConfig{
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManager = new LocalContainerEntityManagerFactoryBean();
entityManager.setDataSource(dataSource());
entityManager.setPackagesToScan("org.vives.model");
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
entityManager.setJpaVendorAdapter(vendorAdapter);
entityManager.setJpaProperties(additionalProperties());
return entityManager;
}
#Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.apache.derby.jdbc.EmbeddedDriver");
dataSource.setUrl("jdbc:derby://localhost:1527/beers;create=true");
dataSource.setUsername( "app" );
dataSource.setPassword( "app" );
return dataSource;
}
#Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManager){
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManager);
return transactionManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
return new PersistenceExceptionTranslationPostProcessor();
}
private Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.DerbyTenSevenDialect");
properties.setProperty("hibernate.transaction.jta.platform", "org.hibernate.service.jta.platform.internal.SunOneJtaPlatform");
properties.setProperty("hibernate.show_sql", "true");
return properties;
}
}
With this code, the application starts without problems.
When i change the Repository and Service like this:
#Repository
public interface BrewerRepository extends CrudRepository<Brewer, Long> {
}
#Service
public class BrewerService {
#PersistenceContext(name = "vivesPU")
private EntityManager entityManager;
#Autowired
private BrewerRepository brewerRepository;
public List<Brewer> getAll() {
return null;
}
}
Error log:
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'homeController': Unsatisfied dependency expressed through field 'brewerService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'brewerService' defined in file [.\glassfish-5.0\glassfish5\glassfish\domains\domain1\applications\spring-mvc-quickstart-1.0-SNAPSHOT\WEB-INF\classes\org\vives\service\BrewerService.class]: Post-processing of merged bean definition failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [org.vives.service.BrewerService] from ClassLoader [WebappClassLoader (delegate=true; repositories=WEB-INF/classes/)]]]
...
Context initialization failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'homeController': Unsatisfied dependency expressed through field 'brewerService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'brewerService' defined in file [.\glassfish-5.0\glassfish5\glassfish\domains\domain1\applications\spring-mvc-quickstart-1.0-SNAPSHOT\WEB-INF\classes\org\vives\service\BrewerService.class]: Post-processing of merged bean definition failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [org.vives.service.BrewerService] from ClassLoader [WebappClassLoader (delegate=true; repositories=WEB-INF/classes/)]
...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'brewerService' defined in file [.\glassfish-5.0\glassfish5\glassfish\domains\domain1\applications\spring-mvc-quickstart-1.0-SNAPSHOT\WEB-INF\classes\org\vives\service\BrewerService.class]: Post-processing of merged bean definition failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [org.vives.service.BrewerService] from ClassLoader [WebappClassLoader (delegate=true; repositories=WEB-INF/classes/)]
...
Caused by: java.lang.IllegalStateException: Failed to introspect Class [org.vives.service.BrewerService] from ClassLoader [WebappClassLoader (delegate=true; repositories=WEB-INF/classes/)]
...
Caused by: java.lang.NoClassDefFoundError: org/springframework/data/repository/CrudRepository
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at org.glassfish.web.loader.WebappClassLoader.findClass(WebappClassLoader.java:1059)
at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1588)
at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1471)
at java.lang.Class.getDeclaredFields0(Native Method)
at java.lang.Class.privateGetDeclaredFields(Class.java:2583)
at java.lang.Class.getDeclaredFields(Class.java:1916)
at org.springframework.util.ReflectionUtils.getDeclaredFields(ReflectionUtils.java:754)
... 82 more
Caused by: java.lang.ClassNotFoundException: org.springframework.data.repository.CrudRepository
at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1621)
at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1471)
... 92 more
]]
I've tried to look for an answer, but without success. Can someone explain to me why this is happening and tell me how I can fix it?
What I've tried so far:
checked the dependencies
deleted the .m2 folder and installed all
dependencies again messed a bit with annotations
changed a bit the project structure, according to this post
EDIT:
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.vives</groupId>
<artifactId>spring-mvc-quickstart</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>spring-mvc-quickstart</name>
<properties>
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java-version>1.8</java-version>
<!-- Override Spring version -->
<spring.version>5.0.0.RELEASE</spring.version>
<jackson.version>2.9.1</jackson.version>
<thymeleaf-extras-java8time-version>3.0.1.RELEASE</thymeleaf-extras-java8time-version>
<!-- AssertJ is not a part of Spring IO platform, so the version must be provided explicitly -->
<assertj-core-version>3.8.0</assertj-core-version>
</properties>
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.1.RELEASE</version>
</dependency>
<!-- Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<!-- Avoid issue #72 Could not initialize class org.thymeleaf.templateresolver.ServletContextTemplateResolver due to 'validation is not supported' -->
<exclusions>
<exclusion>
<artifactId>pull-parser</artifactId>
<groupId>pull-parser</groupId>
</exclusion>
</exclusions>
<version>5.2.9.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>spring-release</id>
<name>Spring Release Repository</name>
<url>https://repo.spring.io/release</url>
</repository>
</repositories>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<compilerArguments>
<endorseddirs>${endorsed.dir}</endorseddirs>
</compilerArguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<outputDirectory>${endorsed.dir}</outputDirectory>
<silent>true</silent>
<artifactItems>
<artifactItem>
<groupId>javax</groupId>
<artifactId>javaee-endorsed-api</artifactId>
<version>7.0</version>
<type>jar</type>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Came to this error [ Caused by: java.lang.ClassNotFoundException: org.springframework.data.repository.CrudRepository ] was using springboot dev tools auto build
but stopped the program -> clean -> run solved the issue on my end.
the CrudRepository class is not found which means that the pom dependencies are not defined well. The Crud repository is defined the spring-data-jpa and it is included but i think the problem could be found in the spring different dependencies that you are using that may conflict with each other. for example some dependencies may be included as a child dependencies in others, so they must not be included again. Also you must make sure that the spring dependencies versions are consistent.
I cleared the .m2 repository (path e.g. C:\Users\Hetal Rachh\.m2\repository) and then did a mvn clean install build and it worked.
The Constructor Injection is missing like:
#Autowired
public BrewerService(BrewerRepository brewerRepository) {
this.brewerRepository = brewerRepository
}
#Override
public List<Brewer> getAll() {
return brewerRepository.findAll();
}
As Amr Alaa mentioned, there was an issue with the dependencies. I solved my problem by creating a new project in a different folder and adding the dependencies again.
I usually update the project and let it rebuild, then restart the program in the spring boot dashboard.

Getting error running spring boot application using -jar

This question has been asked over and over, however I couldn't find my answer. I have an application using spring boot, which intellij can run it without any issue, however java -jar echohostname.jar give me this error:
Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean
Here is my Main class:
public class ApplicationMain {
public static void main(String[] args) {
SpringApplicationBuilder builder = new SpringApplicationBuilder(SpringConfiguration.class);
ConfigurableApplicationContext applicationContext = builder.run(args);
}
This is my Controller class:
#RestController
public class Controller {
#Autowired
#Qualifier("getSigarProxy")
private SigarProxy sigarProxy;
#RequestMapping(value = "/hostname", method = RequestMethod.GET)
public String hostName() throws SigarException {
return "HELLO THERE";
//return sigarProxy.getNetInfo().getHostName();
}
}
And this is spring configuration class:
#SpringBootApplication
#Configuration
#ComponentScan("controller")
public class SpringConfiguration {
#Bean
public static PropertySourcesPlaceholderConfigurer getPropertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
#Bean
public Sigar getSigar() {
return new Sigar();
}
#Bean
public SigarProxy getSigarProxy() {
return SigarProxyCache.newInstance(getSigar(), 1000);
}
#Bean
#Scope("prototype")
public HttpHeaders getHttpHeaders() {
return new HttpHeaders();
}
#Bean
#Scope("prototype")
public AsyncRestTemplate getRestTemplate() {
return new AsyncRestTemplate();
}
}
POM file:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>echoHostname</groupId>
<artifactId>echoHostname</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.fusesource</groupId>
<artifactId>sigar</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<version>1.2.3.RELEASE</version>
</dependency>
</dependencies>
</project>
UPDATED MAIN:
public class ApplicationMain {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(SpringConfiguration.class, args);
}
}
UPDATED 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>echoHostname</groupId>
<artifactId>echoHostname</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.fusesource</groupId>
<artifactId>sigar</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.2.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<version>1.2.7.RELEASE</version>
</dependency>
</dependencies>
</project>
Any help is appreciated.
Add class level #SpringBootApplication annotation in ApplicationMain.java
Add the below plugin in your pom.xml. Build the maven project and execute the jar command
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.6</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
This page has more information on maven assembly plugin - https://maven.apache.org/plugins/maven-assembly-plugin/usage.html
In a spring-boot project, you need that the parent pom be
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
You can remove the spring dependencies, like context, core and beans.
Add to the pom
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
And build the jar again.

Spring Boot with JNDI Data Source

I have a new Spring Boot web application that I want to connect to a JNDI data source (a MySQL database defined in Tomcat's context.xml).
However when I attempt this, I always get the following exception;
org.springframework.beans.factory.BeanCreationException: Cannot determine embedded database url for database type NONE. If you want an embedded database please put a supported on on the classpath.
This is despite my pom.xml containing the MySQL connector
<?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.test</groupId>
<artifactId>twojndi</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Two JNDI Data Sources</name>
<description>Two JNDI Data Sources Example</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.1.8.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<exclusions>
<exclusion>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</exclusion>
<exclusion>
<artifactId>tomcat-jdbc</artifactId>
<groupId>org.apache.tomcat</groupId>
</exclusion>
</exclusions>
</dependency>
<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-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<start-class>org.test.twojndi.Application</start-class>
<java.version>1.7</java.version>
</properties>
<build>
<finalName>${artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
I have defined my application.properties as follows to use the jndi-name property.
spring.datasource.jndi-name=java:comp/env/jdbc/twojndi_ds1
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
However despite that it seems Spring believes that an in-memory database should be used.
I am able to connect to the MySQL database if I define my application.properties as so
spring.datasource.url=jdbc:mysql://localhost:3306/twojndi_ds1
spring.datasource.username=twojndi
spring.datasource.password=twojndi
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
Can anyone help me connect to JNDI with Spring Boot?
As commented by M. Deinum, JDNI lookup is implemented in Spring Boot 1.2, current version is 1.2.0.M2.
If you want to do it with Spring Boot 1.1, you can define a bean like this:
#Bean
public DataSource dataSource() {
JndiObjectFactoryBean jndiObjectFactoryBean = new JndiObjectFactoryBean();
jndiObjectFactoryBean.setJndiName("jdbc/jndidatasource");
try {
jndiObjectFactoryBean.afterPropertiesSet();
} catch (NamingException e) {
LOGGER.error("Error while retrieving datasource with JNDI name jdbc/jndidatasource", e);
}
return (DataSource) jndiObjectFactoryBean.getObject();
}
For me it worked the following configuration, guided by the recipe exposed in this link, but as they said before the same work with versions of spring boot 1.2 or more
public class DomainAndPersistenceJndi {
private JpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
hibernateJpaVendorAdapter.setShowSql(true);
hibernateJpaVendorAdapter.setDatabase(Database.INFORMIX);
hibernateJpaVendorAdapter.setDatabasePlatform("org.hibernate...");
return hibernateJpaVendorAdapter;
}
#Bean(name = "dataSourcejndi")
public DataSource dataSourcejndi() throws NamingException {
JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
bean.setJndiName("java:jboss/datasources/..." );
bean.setProxyInterface(DataSource.class);
bean.setLookupOnStartup(false);
bean.afterPropertiesSet();
return (DataSource) bean.getObject();
}
#Bean(name = "entityManagerFactoryJndi")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryJndi(#Qualifier("dataSourcejndi") DataSource dataSource) {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource( dataSource);
em.setPackagesToScan(EntidadBase.class.getPackage().getName());
em.setJpaVendorAdapter(jpaVendorAdapter());
em.setPersistenceUnitName("BaseDSjdni");
em.afterPropertiesSet();
return em;
}
}

Resources