spring-boot interview questions
Top spring-boot frequently asked interview questions
I have an extra servlet I need to register in my application. However with Spring Boot and its Java Config, I can't just add servlet mappings in a web.xml
file.
How can I add additional servlets?
Source: (StackOverflow)
How to configure nicely Spring Boot application packaged as executable jar as a Service in linux system? Is this recomended approach, or should I convert this app to war and install into Tomcat?
Currently I can run Spring boot application from screen
session, what is nice, but requires manual start after server reboot.
What I'm looking for is general advice/direction or sample init.d script, if my approach with executable jar is proper.
Source: (StackOverflow)
This is very simple question, but I cannot find information.
(Maybe my knowledge about Java frameworks is severely lacking)
How can I set the logging level with application.properties?
And logging file location, etc?
Source: (StackOverflow)
This is the error that is thrown when trying to run my web app:
[INFO] WARNING: Nested in org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.dataSource; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$NonEmbeddedConfiguration.dataSource()] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath.:
[INFO] org.springframework.beans.factory.BeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath.
[INFO] at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.getDriverClassName(DataSourceProperties.java:91)
[INFO] at org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$NonEmbeddedConfiguration.dataSource(DataSourceAutoConfiguration.java:100)
[INFO] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[INFO] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
[INFO] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
[INFO] at java.lang.reflect.Method.invoke(Method.java:606)
[INFO] at com.google.appengine.tools.development.agent.runtime.Runtime.invoke(Runtime.java:115)
[INFO] at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:166)
[INFO] at org.springframework.beans.factory.support.ConstructorResolver$3.run(ConstructorResolver.java:580)
[INFO] at java.security.AccessController.doPrivileged(Native Method)
[INFO] at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:577)
[INFO] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1094)
[INFO] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:989)
[INFO] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
[INFO] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
[INFO] at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
[INFO] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
[INFO] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
[INFO] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
[INFO] at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1017)
[INFO] at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:960)
[INFO] at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858)
[INFO] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
[INFO] at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
[INFO] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
[INFO] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
[INFO] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
[INFO] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
[INFO] at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
[INFO] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
[INFO] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
[INFO] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
[INFO] at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:370)
[INFO] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1094)
[INFO] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:989)
[INFO] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
[INFO] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
[INFO] at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
[INFO] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
[INFO] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
[INFO] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
[INFO] at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:973)
[INFO] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:750)
[INFO] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
[INFO] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:683)
[INFO] at org.springframework.boot.SpringApplication.run(SpringApplication.java:313)
[INFO] at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:142)
[INFO] at org.springframework.boot.legacy.context.web.SpringBootContextLoaderListener.initWebApplicationContext(SpringBootContextLoaderListener.java:60)
[INFO] at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
[INFO] at org.mortbay.jetty.handler.ContextHandler.startContext(ContextHandler.java:548)
[INFO] at org.mortbay.jetty.servlet.Context.startContext(Context.java:136)
[INFO] at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1250)
[INFO] at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:517)
[INFO] at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:467)
[INFO] at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
[INFO] at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)
[INFO] at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
[INFO] at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)
[INFO] at org.mortbay.jetty.Server.doStart(Server.java:224)
[INFO] at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
[INFO] at com.google.appengine.tools.development.JettyContainerService.startContainer(JettyContainerService.java:249)
[INFO] at com.google.appengine.tools.development.AbstractContainerService.startup(AbstractContainerService.java:306)
[INFO] at com.google.appengine.tools.development.AutomaticInstanceHolder.startUp(AutomaticInstanceHolder.java:26)
[INFO] at com.google.appengine.tools.development.AbstractModule.startup(AbstractModule.java:79)
[INFO] at com.google.appengine.tools.development.Modules.startup(Modules.java:88)
[INFO] at com.google.appengine.tools.development.DevAppServerImpl.doStart(DevAppServerImpl.java:254)
[INFO] at com.google.appengine.tools.development.DevAppServerImpl.access$000(DevAppServerImpl.java:47)
[INFO] at com.google.appengine.tools.development.DevAppServerImpl$1.run(DevAppServerImpl.java:212)
[INFO] at com.google.appengine.tools.development.DevAppServerImpl$1.run(DevAppServerImpl.java:210)
[INFO] at java.security.AccessController.doPrivileged(Native Method)
[INFO] at com.google.appengine.tools.development.DevAppServerImpl.start(DevAppServerImpl.java:210)
[INFO] at com.google.appengine.tools.development.DevAppServerMain$StartAction.apply(DevAppServerMain.java:277)
[INFO] at com.google.appengine.tools.util.Parser$ParseResult.applyArgs(Parser.java:48)
[INFO] at com.google.appengine.tools.development.DevAppServerMain.run(DevAppServerMain.java:219)
[INFO] at com.google.appengine.tools.development.DevAppServerMain.main(DevAppServerMain.java:210)
I believe I have the right combination of datanucleus-appengine
and datanucleus
jars:
2.1: Requires DataNucleus 3.1.x (core, api-jdo, api-jpa, enhancer). Requires SDK 1.6.4+ Note that this release of Datanucleus is no longer
supported by the DataNucleus project
JPA App Config:
@Configuration
@EnableJpaRepositories("demo.core.entity")
@EnableTransactionManagement
class JpaApplicationConfig {
private static final Logger logger = Logger
.getLogger(JpaApplicationConfig.class.getName());
@Bean
public AbstractEntityManagerFactoryBean entityManagerFactory() {
logger.info("Loading Entity Manager...");
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setPersistenceUnitName("transactions-optional");
return factory;
}
@Bean
public PlatformTransactionManager transactionManager() {
logger.info("Loading Transaction Manager...");
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory().getObject());
return txManager;
}
@Bean
public PersistenceExceptionTranslator persistenceExceptionTranslator() {
return new OpenJpaDialect();
}
}
Application.java
@Configuration
@ComponentScan
@EnableAutoConfiguration
@RestController
public class Application {
private static final EntityManagerFactory INSTANCE =
Persistence.createEntityManagerFactory("transactions-optional");
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@RequestMapping("/")
public String home() {
return "Hello World";
}
}
POM:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="...">
<modelVersion>4.0.0</modelVersion>
<groupId>org.demohq</groupId>
<artifactId>demo-boot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>demo-boot</name>
<description>Demo project</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.1.0.BUILD-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</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-legacy</artifactId>
<version>1.1.0.BUILD-SNAPSHOT</version>
</dependency>
<!--<dependency>-->
<!--<groupId>net.kindleit</groupId>-->
<!--<artifactId>gae-runtime</artifactId>-->
<!--<version>${gae.version}</version>-->
<!--<type>pom</type>-->
<!--<scope>provided</scope>-->
<!--</dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</dependency>
<!--<dependency>-->
<!--<groupId>org.hsqldb</groupId>-->
<!--<artifactId>hsqldb</artifactId>-->
<!--<scope>runtime</scope>-->
<!--</dependency>-->
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-api-labs</artifactId>
<version>${gae.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-api-stubs</artifactId>
<version>${gae.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-testing</artifactId>
<version>${gae.version}</version>
<scope>test</scope>
</dependency>
<!-- DataNucleus -->
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-api-jpa</artifactId>
<version>${datanucleus.jpa.version}</version>
</dependency>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-core</artifactId>
<version>${datanucleus.jpa.version}</version>
</dependency>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-enhancer</artifactId>
<version>${datanucleus.jpa.version}</version>
</dependency>
<dependency>
<groupId>com.google.appengine.orm</groupId>
<artifactId>datanucleus-appengine</artifactId>
<version>${datanucleus.version}</version>
<!-- Need to exclude the enhancer since it interfere with the enhancer plugin. -->
<exclusions>
<exclusion>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-enhancer</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>javax.jdo</groupId>
<artifactId>jdo-api</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-jpa_2.0_spec</artifactId>
<version>1.1</version>
</dependency>
<!-- OpenJPA -->
<dependency>
<groupId>org.apache.openjpa</groupId>
<artifactId>openjpa-persistence</artifactId>
<version>2.3.0</version>
</dependency>
</dependencies>
<properties>
<start-class>demo.Application</start-class>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.7</java.version>
<m2eclipse.wtp.contextRoot>/</m2eclipse.wtp.contextRoot>
<datanucleus.jpa.version>3.1.1</datanucleus.jpa.version>
<datanucleus.version>2.1.2</datanucleus.version>
<gae.version>1.8.8</gae.version>
<gae.home>${settings.localRepository}/com/google/appengine/appengine-java-sdk/${gae.version}/appengine-java-sdk/appengine-java-sdk-${gae.version}</gae.home>
<gae.application.version>test</gae.application.version>
<!--<org.springframework-version>4.0.5.RELEASE</org.springframework-version>-->
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!--
<plugin>
<groupId>net.kindleit</groupId>
<artifactId>maven-gae-plugin</artifactId>
<version>0.9.6</version>
<dependencies>
<dependency>
<groupId>net.kindleit</groupId>
<artifactId>gae-runtime</artifactId>
<version>${gae.version}</version>
<type>pom</type>
</dependency>
</dependencies>
</plugin>
-->
<plugin>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-maven-plugin</artifactId>
<version>${gae.version}</version>
<configuration>
<enableJarClasses>false</enableJarClasses>
</configuration>
</plugin>
<plugin>
<artifactId>maven-release-plugin</artifactId>
<configuration>
<goals>gae:deploy</goals>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat6-maven-plugin</artifactId>
<version>2.0</version>
<configuration>
<path>/</path>
</configuration>
</plugin>
<plugin>
<groupId>org.datanucleus</groupId>
<artifactId>maven-datanucleus-plugin</artifactId>
<version>${datanucleus.jpa.version}</version>
<configuration>
<api>JPA</api>
<!--<mappingIncludes>**/entity/*.class</mappingIncludes>-->
<verbose>true</verbose>
</configuration>
<dependencies>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-core</artifactId>
<version>${datanucleus.jpa.version}</version>
</dependency>
</dependencies>
<executions>
<execution>
<phase>compile</phase>
<goals>
<goal>enhance</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<profiles>
<!-- We can configure our integration server to activate this profile and
perform gae:deploy, thus uploading latest snapshot to the http://1.latest.<applicationName>.appspot.com
automatically -->
<profile>
<id>integration-build</id>
<properties>
<gae.application.version>stage</gae.application.version>
</properties>
</profile>
<!-- This profile will activate automatically during release and upload
application to the http://2.latest.<applicationName>.appspot.com (We might
want to set the 2nd version as our applications Default version to be accessible
at http://<applicationName>.appspot.com) -->
<profile>
<id>release-build</id>
<activation>
<property>
<name>performRelease</name>
<value>true</value>
</property>
</activation>
<properties>
<!-- During release, set application version in appengine-web.xml to
2 -->
<gae.application.version>release</gae.application.version>
</properties>
</profile>
</profiles>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>http://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>http://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>http://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>http://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>
I wonder what could be missing in my app? I followed the instruction from here Using Spring Data JPA on Google Appengine
Source: (StackOverflow)
I am testing a business service with TestNG, mockito unit tests in spring boot application.
Application is multi-module spring boot project.And I am writing unit tests for business module.
I have added following dependencies related testing in pom,
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>el-api</artifactId>
<version>${javaxel.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.servlet</artifactId>
<version>${javax.servlet.version}</version>
<scope>test</scope>
</dependency>
My wrapper annotation look like
@Service
@Transactional
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface MyServiceAnnotation{}
My TestApp looks like
@SpringBootApplication
public class TestApp{ .... }
My Business Service looks like
@MyServiceAnnotation
public class AddressServiceImpl implements AddressService {
@Autowire
UserDAO userDAO;
@Autowire
AddressDAO addressDAO;
public Address find(int userId) {
user = userDAO.findOne(userId);
/** if I run following test then I get user NULL.
But it should get user object which I have created
in data provider
**/
if(user == null ) { throw new BadReqExcp("invalid user Id", 101); }
address = user.findAddresses();
if(address is empty) { throw new BadReqExcp("add not found", 102);}
return address;
}
}
MyTestClass looks like
@ContextConfiguration(classes = { TestApp.class })
class MyTestClass{
@Mock
UserDAO userDAO;
@InjectMocks
@Autowire
AddressService addressServie;
@BeforeMethod
public void initMock() {
MockitoAnnotations.initMocks(this);
}
@Test(dataProvider = "getUser", dataProviderclass = UserDP.class)
public void shouldThrowExceptionAddressNotFound(int userId, User user)
{
when(userDAO.findOne(userId)).thenReturn(user); //here dao call should return user but it is returning null
try{
addressService.find(userId);
}
catch(BadReqExcp e){
// Here errro code should be 102 but fount 101
assertEquals(e.getErrorCode(), 102);
}
}
}
If I don't use @Target(ElementType.TYPE)
, @Retention(RetentionPolicy.RUNTIME)
, @Inherited
these annotations then my mock DAO calls in test works fine.
I need above annotations explicitly because if I do not use them then,
For example, If I want to perform one single task which uses multiple business service then they wont happen in ONE transaction.
In other words if a business call uses multiple business services say ServiceA
and ServiceB
. Call goes from serviceA
to serviceB
. If an exception occurs in serviceB
then database changes done by serviceA
wont rollback.
When I use above annotations then above example works BUT mock DAO calls in junit tests does not works.
Do I have wrong dependencies in pom?
- Why this is not working ?
- What would be the solution over it ?
Git Repository Source Code , here you will get sample code.It is giving me some error while compiling.
Source: (StackOverflow)
I have recently been spending some time looking over projects contained in the Spring 4.0 ecosystem and have recently come across the documentation for Spring Boot. It appears that Boot has a bunch of nice features for getting a Spring application up and running quickly, including the ability to auto configure and run embedded application servers in a simple .jar file. I realize that Roo is meant to be more of a CLI tool for quickly prototyping a Spring application and does not take as much of an 'opinionated' approach as Boot. Despite these differences, both tools have the end goal of making it easier to stand up a Spring application from scratch, so my question is the following: Is Spring Boot meant to replace Spring Roo in the Spring ecosystem, or will they both continue to co-exist with the same level of support?
Source: (StackOverflow)
I am trying to set a Spring Boot applications context root programatically. The reason for the context root is we want the app to be accessed from localhost:port/{app_name} and have all the controller paths append to it.
Here is the application configuration file for the web-app.
@Configuration
public class ApplicationConfiguration {
Logger logger = LoggerFactory.getLogger(ApplicationConfiguration.class);
@Value("${mainstay.web.port:12378}")
private String port;
@Value("${mainstay.web.context:/mainstay}")
private String context;
private Set<ErrorPage> pageHandlers;
@PostConstruct
private void init(){
pageHandlers = new HashSet<ErrorPage>();
pageHandlers.add(new ErrorPage(HttpStatus.NOT_FOUND,"/notfound.html"));
pageHandlers.add(new ErrorPage(HttpStatus.FORBIDDEN,"/forbidden.html"));
}
@Bean
public EmbeddedServletContainerFactory servletContainer(){
TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory();
logger.info("Setting custom configuration for Mainstay:");
logger.info("Setting port to {}",port);
logger.info("Setting context to {}",context);
factory.setPort(Integer.valueOf(port));
factory.setContextPath(context);
factory.setErrorPages(pageHandlers);
return factory;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
}
Here is the index controller for the main page.
@Controller
public class IndexController {
Logger logger = LoggerFactory.getLogger(IndexController.class);
@RequestMapping("/")
public String index(Model model){
logger.info("Setting index page title to Mainstay - Web");
model.addAttribute("title","Mainstay - Web");
return "index";
}
}
The new root of the application should be at localhost:12378/mainstay but it is still located at localhost:12378.
What am I missing that is causing Spring Boot to not append the context root before the request mapping?
Source: (StackOverflow)
I'm trying to remove white label error page, so what I've done was created a controller mapping for "/error",
@RestController
public class IndexController {
@RequestMapping(value = "/error")
public String error() {
return "Error handling";
}
}
But now I"m getting this error.
Exception in thread "AWT-EventQueue-0" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping found. Cannot map 'basicErrorController' bean method
public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletR equest)
to {[/error],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}: There is already 'indexController' bean method
Don't know whether I'm doing anything wrong. Please advice.
EDIT:
Already added
error.whitelabel.enabled=false
to application.properties file, still getting the same error
Source: (StackOverflow)
Is there a specific recommended approach to the inclusion of the spring-boot parent pom into projects that already have a required parent POM?
What do you recommend for projects that need to extend from an organizational parent (this is extremely common and even something many/most projects published to Maven central depending on the feeder repos they come from). Most of the build stuff is related to creating executable JARs (e.g. running embedded Tomcat/Jetty). There are ways to structure things so that you can get all the dependencies without extending from a parent (similar to composition vs. inheritance). You can't get a build stuff that way though.
So is it preferable to include all of the spring-boot parent pom inside of the required parent POM or to simply have a POM dependency within the project POM file.
Other options?
TIA,
Scott
Source: (StackOverflow)
I'm banging my head against the wall for a couple of hours now. My project is almost finished, but I can't get it to serve static content.
I've placed a folder named static
under src/main/resources
. Inside it I have a folder named images
. When I package the app and run it, it can't find the images I have put on that folder.
I've tried to put the static files in public
, resources
and META-INF/resources
but nothing works.
If I jar -tvf app.jar I can see that the files are inside the jar on the right folder:
/static/images/head.png
for example, but calling: http://localhost:8080/images/head.png
, all I get is a 404
Any ideas why spring-boot is not finding this? (I'm using 1.1.4 BTW)
Source: (StackOverflow)
I'm quite new to spring boot and I'd like to create a multiple datasource for my project.
Here is my current case. I have two packages for entity for multiple database. Let's say
com.test.entity.db.mysql ; for entities that belong to MySql
com.test.entity.db.h2 ; for entities that belong to H2 Databases
So, currently I have two entities class
UserMySql.java
@Entity
@Table(name="usermysql")
public class UserMysql{
@Id
@GeneratedValue
public int id;
public String name;
}
UserH2.java
@Entity
@Table(name="userh2")
public class Userh2 {
@Id
@GeneratedValue
public int id;
public String name;
}
I'd like to achieve a configuration where if I create user from UserMySql, it will be saved to MySql Database, and if I create user from Userh2 it will be saved to H2 Databases. So, I also have two DBConfig, let's say MySqlDbConfig and H2DbConfig.
(com.test.model is package where I'll put my Repositories class. It will be defined below)
MySqlDbConfig.java
@Configuration
@EnableJpaRepositories(
basePackages="com.test.model",
entityManagerFactoryRef = "mysqlEntityManager")
public class MySqlDBConfig {
@Bean
@Primary
@ConfigurationProperties(prefix="datasource.test.mysql")
public DataSource mysqlDataSource(){
return DataSourceBuilder
.create()
.build();
}
@Bean(name="mysqlEntityManager")
public LocalContainerEntityManagerFactoryBean mySqlEntityManagerFactory(
EntityManagerFactoryBuilder builder){
return builder.dataSource(mysqlDataSource())
.packages("com.test.entity.db.mysql")
.build();
}
}
H2DbConfig.java
@Configuration
@EnableJpaRepositories(
entityManagerFactoryRef = "h2EntityManager")
public class H2DbConfig {
@Bean
@ConfigurationProperties(prefix="datasource.test.h2")
public DataSource h2DataSource(){
return DataSourceBuilder
.create()
.driverClassName("org.h2.Driver")
.build();
}
@Bean(name="h2EntityManager")
public LocalContainerEntityManagerFactoryBean h2EntityManagerFactory(
EntityManagerFactoryBuilder builder){
return builder.dataSource(h2DataSource())
.packages("com.test.entity.db.h2")
.build();
}
}
My application.properties file
#DataSource settings for mysql
datasource.test.mysql.jdbcUrl = jdbc:mysql://127.0.0.1:3306/test
datasource.test.mysql.username = root
datasource.test.mysql.password = root
datasource.test.mysql.driverClassName = com.mysql.jdbc.Driver
#DataSource settings for H2
datasource.test.h2.jdbcUrl = jdbc:h2:~/test
datasource.test.h2.username = sa
# DataSource settings: set here configurations for the database connection
spring.datasource.url = jdbc:mysql://127.0.0.1:3306/test
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.validation-query=SELECT 1
# Specify the DBMS
spring.jpa.database = MYSQL
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate settings are prefixed with spring.jpa.hibernate.*
spring.jpa.hibernate.ddl-auto = update
spring.jpa.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.naming_strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.hibernate.show_sql = true
spring.jpa.hibernate.format_sql = true
server.port=8080
endpoints.shutdown.enabled=false
And then for crud I have UserMySqlDao and UserH2Dao
UserMySqlDao.java
@Transactional
@Repository
public interface UserMysqlDao extends CrudRepository<UserMysql, Integer>{
public UserMysql findByName(String name);
}
UserH2Dao.java
@Transactional
@Repositories
public interface UserH2Dao extends CrudRepository<Userh2, Integer>{
public Userh2 findByName(String name);
}
And for last, I have an UserController as endpoint to access my service
UserController.java
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserMysqlDao userMysqlDao;
@Autowired
private UserH2Dao userH2Dao;
@RequestMapping("/createM")
@ResponseBody
public String createUserMySql(String name){
UserMysql user = new UserMysql();
try{
user.name = name;
userMysqlDao.save(user);
return "Success creating user with Id: "+user.id;
}catch(Exception ex){
return "Error creating the user: " + ex.toString();
}
}
@RequestMapping("/createH")
@ResponseBody
public String createUserH2(String name){
Userh2 user = new Userh2();
try{
user.name = name;
userH2Dao.save(user);
return "Success creating user with Id: "+user.id;
}catch(Exception ex){
return "Error creating the user: " + ex.toString();
}
}
}
Application.java
@Configuration
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
@EntityScan(basePackages="com.test.entity.db")
@ComponentScan
public class Application {
public static void main(String[] args) {
System.out.println("Entering spring boot");
ApplicationContext ctx = SpringApplication.run(Application.class, args);
System.out.println("Let's inspect the beans provided by Spring Boot:");
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.print(beanName);
System.out.print(" ");
}
System.out.println("");
}
}
With this configuration my Spring boot run well, but when I access
http://localhost/user/createM?name=myname it writes an exception
Error creating the user: org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute statement; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute statement
I've googling around and haven't got a solution yet. Any ideas why this exception occurs? And is this the best way to implement multiple datasource to implement my case above? I'm open to full refactor if needed.
Thanks
Source: (StackOverflow)
I have a Spring Boot web application, and I would like to serve static content located in a shared Dropbox directory on my Linode VPS (~/Dropbox/images). I've read that Spring Boot will automatically serve static content from
"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/",
but of course my Dropbox directory is not on the classpath.
Although I could configure Apache to serve the images in my Dropbox folder, I would like to take advantage of Spring Security to restrict access of the static content to authenticated users.
Source: (StackOverflow)
How can I override the favicon of Spring Boot?
NOTE: Here is my another question that provides another solution which does not involve any coding: Spring Boot: Is it possible to use external application.properties files in arbitrary directories with a fat jar? It's for application.properties, but it can also be applied to the favicon. In fact, I'm using that method for favicon overriding now.
If I implement a class that has @EnableWebMvc, WebMvcAutoConfiguration class of Spring Boot does not load, and I can serve my own favicon by placing it to the root directory of the static contents.
Otherwise, WebMvcAutoConfiguration registers faviconRequestHandler bean, (see source https://github.com/spring-projects/spring-boot/blob/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration.java) and it serve the 'green leaf' icon which is placed in the Spring Boot's main resource directory.
How can I override it without implementing a class that has @EnableWebMvc myself, thus disabling whole default configuration functionality of WebMvcAutoConfiguration class of Spring Boot?
Also, since I want the icon file be updated as soon as possible on the client (web browser) side, I want to set the cache period of the favicon file to 0. (like the following code, which I'm using for my 'static' webapp content and script files which must be updated on the client side as soon as possible after I change the file.)
public void addResourceHandlers(ResourceHandlerRegistry registry)
{
registry.addResourceHandler("/**")
.addResourceLocations("/")
.setCachePeriod(0);
}
So, just to find the place to save the favicon.ico file that Spring Boot's faviconRequestHandler honors may not be sufficient.
UPDATE
Now I know that I can override the default one by placing a favicon file to src/main/resources directory. But the cache period problem still remains.
Also, it is preferable to place the favicon file to the directory that static web files are placed, rather than the resource directory.
UPDATE
Ok, I managed to override the default one.
What I did is as follows:
@Configuration
public class WebMvcConfiguration
{
@Bean
public WebMvcConfigurerAdapter faviconWebMvcConfiguration()
{
return new FaviconWebMvcConfiguration();
}
public class FaviconWebMvcConfiguration extends WebMvcConfigurerAdapter
{
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry)
{
registry.setOrder(Integer.MIN_VALUE);
registry.addResourceHandler("/favicon.ico")
.addResourceLocations("/")
.setCachePeriod(0);
}
}
}
Basically, I overrode the default one by adding a resource handler with the highest order by calling registry.setOrder(Integer.MIN_VALUE).
Since the default one in Spring Boot has the order value (Integer.MIN_VALUE + 1), (see FaviconConfiguration class in https://github.com/spring-projects/spring-boot/blob/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration.java) my handler wins.
Is this Ok?
Is there another way (something gentler than what I did)?
UPDATE
It's not Ok.
When I call registry.setOrder(Integer.MIN_VALUE)
, actually I raise the priority of all resource handlers. So, when I add following code to another WebMvcConfigurerAdapter
, effectively all http request is directed to that resource handler, preventing any dynamic handling by Java code.
public void addResourceHandlers(ResourceHandlerRegistry registry)
{
registry.addResourceHandler("/**")
.addResourceLocations("/")
.setCachePeriod(0);
}
Another solution is needed.
UPDATE
For now, I could not find the way to override the favicon functionality Spring Boot provides.
Maybe there is a way to add add my own HandlerMapping
bean, but I don't know how to do it.
Now I can choose one of following options:
- Have a class that has
@EnableWebMvc
thus disabling Spring Boot WebMvcAutoConfiguration
class. (I can copy the code of WebMvcAutoConfiguration
class and delete the favicon functionality)
- Give up the freedom of placing favicon file to arbitary location and place it to the resource directory as Spring Boot's favicon functionality requires. And ignore caching problem.
But neither option is satisfactory.
I just want to place the favicon file with my static web files (which can be any directory since I can change the document root) and resolve the caching problem.
Am I missing something?
Any suggestion would be greatly appreciated.
UPDATE
BTW, the reason I want to change the location of favicon and other static files is as follows. For now it is mainly the development environment issue.
I'm building a single page web application(SPA).
Libraries/Frameworks:
- For server side, I use Spring. (of course)
- For client (web browser) side, I use AngularJS.
Tools:
- For server side, I use Spring Tool Suite.
- For client side, I use WebStorm.
Main directory structure:
ProjectRoot\
src\
bin\
build\
webapp\
build.gradle
- src: Where my Spring java source files reside.
- bin: Where Spring Tool Suite places its build output.
- build: Where 'gradle build' places its build output.
- webapp: Where my client source files(.js, .css, .htm and favicon) reside. Thus this is the WebStorm project directory. (I can change the directory name if necessary)
What I want is:
- To be able to modify and test my client code without rebuilding/restarting my Spring server application. So, the client code must not be put into the jar file. Anyways Spring Tool Suite does not build a jar file at all (at least for the current configuration)
- To be able to test my Spring server application with the client code, easily switching between Spring Tool Suite output and gradle output. So, client code must be accessible from both the server application in
build
subdirectory (actually build\libs
) and the server application in bin
directory.
- When I modify the client code, it must be immediately available to the web browser. So browser must not cache it indefinitely, and must always ask for the server for update.
- When deployed, client code must be modifiable without rebuilding/restarting the server application. So the client code must not be put into the jar file.
Regarding cache issue:
Without setCachePeriod(0) on addResourceHandlers(), Google Chrome caches the file indefinitely, without asking the server for updates. It does not even connect to the server. (Google engineers say that the behavior is correct.) So, all I can do is to manually clear the browser cache. It is frustrating on development environment, and unacceptable on production environment.
BTW, express.js module on Node.js gives reasonable default HTTP header so that Google Chrome ask the server for updates. When I reviewed the HTTP headers that Spring and express.js produces using Fiddler, they were different.
Any suggestion for improving my environment would be appreciated.
Since I'm a Spring beginner, I may be missing something.
UPDATE
Finally I have a working code. It is as follows:
@Configuration
public static class FaviconConfiguration
{
@Bean
public SimpleUrlHandlerMapping myFaviconHandlerMapping()
{
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
mapping.setOrder(Integer.MIN_VALUE);
mapping.setUrlMap(Collections.singletonMap("/favicon.ico",
myFaviconRequestHandler()));
return mapping;
}
@Autowired
ApplicationContext applicationContext;
@Bean
protected ResourceHttpRequestHandler myFaviconRequestHandler()
{
ResourceHttpRequestHandler requestHandler =
new ResourceHttpRequestHandler();
requestHandler.setLocations(Arrays
.<Resource> asList(applicationContext.getResource("/")));
requestHandler.setCacheSeconds(0);
return requestHandler;
}
}
Notice the bean names. I have added 'my' to avoid name clash.
Autowiring application context itself seems awkward, but it was neccessary for mimicking the code in org.springframework.web.servlet.config.annotation.ResourceHandlerRegistration.addResourceLocations()
.
Now I have a favicon handler free of caching problem, and I can place the favicon file anywhere I want.
Thanks.
Source: (StackOverflow)
I am totally new to Spring and started to do the official guides from this site:
https://spring.io/guides
I'd like to do this guide:
https://spring.io/guides/gs/scheduling-tasks/
I get the following Exception:
2014-02-14 16:25:21.614 INFO 9032 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.scheduling.annotation.SchedulingConfiguration' of type [class org.springframework.scheduling.annotation.SchedulingConfiguration$$EnhancerByCGLIB$$5b48d763] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2014-02-14 16:25:21.638 INFO 9032 --- [ main] .c.l.ClasspathLoggingApplicationListener : Application failed to start with classpath: [file:/C:/work/Spring/SpringTutorial/target/classes/, file:/C:/work/apache-maven-3.0.3/repo/javax/servlet/javax.servlet-api/3.0.1/javax.servlet-api-3.0.1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-starter/1.0.0.RC1/spring-boot-starter-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot/1.0.0.RC1/spring-boot-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-core/4.0.0.RELEASE/spring-core-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-context/4.0.0.RELEASE/spring-context-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-autoconfigure/1.0.0.RC1/spring-boot-autoconfigure-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-starter-logging/1.0.0.RC1/spring-boot-starter-logging-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/slf4j/jcl-over-slf4j/1.7.5/jcl-over-slf4j-1.7.5.jar, file:/C:/work/apache-maven-3.0.3/repo/org/slf4j/slf4j-api/1.7.5/slf4j-api-1.7.5.jar, file:/C:/work/apache-maven-3.0.3/repo/org/slf4j/jul-to-slf4j/1.7.5/jul-to-slf4j-1.7.5.jar, file:/C:/work/apache-maven-3.0.3/repo/org/slf4j/log4j-over-slf4j/1.7.5/log4j-over-slf4j-1.7.5.jar, file:/C:/work/apache-maven-3.0.3/repo/ch/qos/logback/logback-classic/1.0.13/logback-classic-1.0.13.jar, file:/C:/work/apache-maven-3.0.3/repo/ch/qos/logback/logback-core/1.0.13/logback-core-1.0.13.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-starter-web/1.0.0.RC1/spring-boot-starter-web-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-starter-tomcat/1.0.0.RC1/spring-boot-starter-tomcat-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/apache/tomcat/embed/tomcat-embed-core/7.0.47/tomcat-embed-core-7.0.47.jar, file:/C:/work/apache-maven-3.0.3/repo/org/apache/tomcat/embed/tomcat-embed-logging-juli/7.0.47/tomcat-embed-logging-juli-7.0.47.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-web/4.0.0.RELEASE/spring-web-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/aopalliance/aopalliance/1.0/aopalliance-1.0.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-aop/4.0.0.RELEASE/spring-aop-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-beans/4.0.0.RELEASE/spring-beans-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-webmvc/4.0.0.RELEASE/spring-webmvc-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-expression/4.0.0.RELEASE/spring-expression-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/com/fasterxml/jackson/core/jackson-databind/2.3.1/jackson-databind-2.3.1.jar, file:/C:/work/apache-maven-3.0.3/repo/com/fasterxml/jackson/core/jackson-annotations/2.3.0/jackson-annotations-2.3.0.jar, file:/C:/work/apache-maven-3.0.3/repo/com/fasterxml/jackson/core/jackson-core/2.3.1/jackson-core-2.3.1.jar, file:/C:/work/apache-maven-3.0.3/repo/commons-lang/commons-lang/2.2/commons-lang-2.2.jar]
Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:140)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:476)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:124)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:658)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:355)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:920)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:909)
at hu.kumite.Application.main(Application.java:17)
Caused by: org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.getEmbeddedServletContainerFactory(EmbeddedWebApplicationContext.java:190)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:163)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:137)
... 7 more
The application starter class is this:
@ComponentScan
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
//SpringApplication.run(Application.class, args);
SpringApplication.run(ScheduledTasks.class, args);
}
}
As you can see, the main method contains a commented line. I've already done a tutorial, namely this one: https://spring.io/guides/gs/consuming-rest/
It's up and running. But I can't run the ScheduledTasks app, which is the following:
@EnableScheduling
public class ScheduledTasks {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
System.out.println("The time is now " + dateFormat.format(new Date()));
}
}
I use Eclipse and run the Application.java's main as an Application.
Could someone please help me?
Source: (StackOverflow)
I am trying run a spring-boot application which uses hibernate via spring-jpa, but i am getting this error:
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:104)
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:71)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:205)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1885)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1843)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:843)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:398)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:842)
at org.hibernate.jpa.HibernatePersistenceProvider.createContainerEntityManagerFactory(HibernatePersistenceProvider.java:152)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:336)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1613)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1550)
... 21 more
my pom.xml file is this:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.1.8.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
</dependency>
</dependencies>
my hibernate configuration is that (the dialect configuration is in the last method from this class):
@Configuration
@EnableTransactionManagement
@ComponentScan({ "com.spring.app" })
public class HibernateConfig {
@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(restDataSource());
sessionFactory.setPackagesToScan(new String[] { "com.spring.app.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
@Bean
public DataSource restDataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("org.postgresql.Driver");
dataSource.setUrl("jdbc:postgresql://localhost:5432/teste?charSet=LATIN1");
dataSource.setUsername("klebermo");
dataSource.setPassword("123");
return dataSource;
}
@Bean
@Autowired
public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(sessionFactory);
return txManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
Properties hibernateProperties() {
return new Properties() {
/**
*
*/
private static final long serialVersionUID = 1L;
{
setProperty("hibernate.hbm2ddl.auto", "create");
setProperty("hibernate.show_sql", "false");
setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
}
};
}
}
what I am doing wrong here?
Source: (StackOverflow)