Injecting Specific DataSource in Spring Boot 2.0.2 Release - spring

When trying to autowire DataSource by using Spring Boot 2.0.2 RELEASE, it gives the following error and cannot manage to inject it:
'Could not autowire. There is more than one bean of 'DataSource' type.'
The beans are created in DataSourceConfiguration class for HikariDataSource, BasicDataSource and for Tomcat.
Is there a way of qualifying one of them and avoid creation of the remaining ones?
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
public SecurityConfig() {
this.usersByUsernameQuery = // definitions here
this.authoritiesByUsernameQuery = //
this.allowedAuthorities = //
}
#Autowired
public void configureGlobal(final AuthenticationManagerBuilder auth, final DataSource dataSource) throws Exception {
auth.jdbcAuthentication()
.dataSource(dataSource)
.usersByUsernameQuery(usersByUsernameQuery)
.authoritiesByUsernameQuery(authoritiesByUsernameQuery);
}
}
pom.xml:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
</dependencies>
application.properties:
spring.datasource.url=jdbc:mysql://localhost:9400/test
spring.datasource.username=root
spring.datasource.password=test
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

Related

How to resolve javax.servlet.ServletException: Circular view path for basic Spring Security?

Im new to Spring Boot and was trying to implement basic Spring Security for a single endpoint in my Spring Boot controller. But I dont know how to resolve the Circular View Error
My Controller
#Controller
#RequestMapping("/api")
public class HelloSecurityController {
#RequestMapping({"/hello"})
public static String helloWorld() {
return "hello";
}
My Security Configurer Class
#EnableWebSecurity
public class SecurityConfigurer extends WebSecurityConfigurerAdapter {
#Autowired
private MyUserDetailsService myUserDetailsService;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(myUserDetailsService);
}
#Bean
public PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
```
My MyUserDetailsService which returns a simple User with Password
#Service
public class MyUserDetailsService implements UserDetailsService {
#Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
return new User("foo","foo", new ArrayList<>());
The Dependencies I kept in maven pom file during initializing Spring Boot Project
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
The Package structure of my project:
proj_struct
After logging in using the username and password at the login form page generated by spring security Im getting the error:
javax.servlet.ServletException: Circular view path [hello]: would dispatch back to the current handler URL [/api/hello] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)
I have not kept any static template (HTML/JSP) in the templates folder. I dont know if I have to as after login I just want to see a simple String. How do I resolve this?

No ServletContext set error while Autowiring AuthenticationManager in WsConfigurerAdapter

I have spring boot application which is using 'spring-boot-starter-security', 'spring-ws-security', 'spring-boot-starter-web-services'
I am facing below error while autowiring AuthenticationManager .
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'resourceHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'resourceHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException: No ServletContext set
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'resourceHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException: No ServletContext set
Caused by: java.lang.IllegalStateException: No ServletContext set
I am trying to upgrade my spring boot application from 1.4.6 to 2.3.9.
My pom dependencies are
<name>
testproject</name>
<groupId>com.test</groupId>
<artifactId>test-integration</artifactId>
<version>0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.9.RELEASE</version>
</parent>
<properties>
<jdk.version>11</jdk.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-security</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.sun.xml.wss</groupId>
<artifactId>xws-security</artifactId>
<version>3.0</version>
<exclusions>
<exclusion>
<groupId>javax.xml.crypto</groupId>
<artifactId>xmldsig</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>wsdl4j</groupId>
<artifactId>wsdl4j</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
<version>6.0.8</version>
</dependency>
<dependency>
<groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId>
<version>15.0</version>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
<version>1.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.7.0</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
<version>1.4.199</version>
</dependency>
<dependency>
<groupId>org.flywaydb.flyway-test-extensions</groupId>
<artifactId>flyway-spring-test</artifactId>
<version>6.3.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>xmlunit</groupId>
<artifactId>xmlunit</artifactId>
<version>1.6</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-properties-migrator</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
My WebSecurityConfigurerAdapter
class AuthenticationConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
private PasswordEncoder passwordEncoder;
#Autowired
DatabaseUserDetailsService databaseUserDetailsService;
#Bean
public DaoAuthenticationProvider daoAuthenticationProvider() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(databaseUserDetailsService);
provider.setPasswordEncoder(passwordEncoder);
return provider;
}
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(daoAuthenticationProvider());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().permitAll()
.and().httpBasic().disable()
.csrf().disable();
}
}
My WsConfigurerAdapter
#EnableWs
#Configuration
//#EnableWebSecurity
#EnableRetry
public class WebServiceConfig extends WsConfigurerAdapter {
#Autowired
AuthenticationManager authenticationManager;
// Default to proper production url if not set.
#Value("${wsdl.address.prefix}")
private String wsdlAddressPrefix = <url>;
#Bean
public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) {
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext);
servlet.setTransformWsdlLocations(false);
return new ServletRegistrationBean(servlet, "<path>");
}
#Bean(name = "stampedWorkingTimeEvents")
public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema stampedWorkingTimeEventsSchema) {
DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
wsdl11Definition.setPortTypeName(<port>);
wsdl11Definition.setLocationUri(<uri>);
wsdl11Definition.setTargetNamespace(<namespace>);
wsdl11Definition.setSchema(stampedWorkingTimeEventsSchema);
return wsdl11Definition;
}
#Bean
public XsdSchema stampedWorkingTimeEventsSchema() {
return new SimpleXsdSchema(new ClassPathResource(<xsd>));
}
#Bean
XwsSecurityInterceptor securityInterceptor() {
XwsSecurityInterceptor securityInterceptor = new XwsSecurityInterceptor();
securityInterceptor.setCallbackHandler(plainTextPasswordValidationCallbackHandler());
securityInterceptor.setPolicyConfiguration(new ClassPathResource("securityPolicy.xml"));
return securityInterceptor;
}
#Bean
SpringPlainTextPasswordValidationCallbackHandler plainTextPasswordValidationCallbackHandler() {
SpringPlainTextPasswordValidationCallbackHandler callbackHandler = new SpringPlainTextPasswordValidationCallbackHandler();
callbackHandler.setAuthenticationManager(authenticationManager);
return callbackHandler;
}
#Override
public void addInterceptors(List<EndpointInterceptor> interceptors) {
interceptors.add(securityInterceptor());
}
}
I have also tried excluding WebMvcAutoConfiguration,
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration
but it again gives me below error on other functionality since it is dependent on this
org.springframework.http.converter.HttpMessageNotWritableException

Unable to resolve a bean for 'javax.persistence.EntityManager'

I had an embedded project, this was a war, I configured Spring Boot and this was deployed sucessfully on Wildfly 13.
My problem is that I moved the repositories and services of Spring Boot to another module, another jar, and from the web application, I added the dependency to this jar. I changed the package name of the classes, the EntityScan and the ComponentScan to the new packages, but I am having the same error.
The goal is to deploy sucessfully my web application on Wildfly 13 using this component separated, the business logic.
I am running this on Java 8, Wildfly 13, Maven 3.3.9 and Spring Boot 2.1.2.RELEASE.
I've tried a lot of suggestions in the Internet, but I coudn't.
This class I put in the jar separated to the web application:
#Configuration
#EnableAutoConfiguration
#ComponentScan(basePackages = {"io.quarzo.service"})
#EntityScan(basePackages = "io.quarzo.domain.model.entities")
#EnableJpaRepositories(basePackages = "io.quarzo.service", entityManagerFactoryRef = "entityManagerFactory")
#EnableTransactionManagement
public class RepositoryConfiguration {
#Bean
public DataSource jndiDataSource() throws IllegalArgumentException, NamingException {
JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
bean.setJndiName("java:/QuarzoDs");
bean.setProxyInterface(DataSource.class);
bean.setLookupOnStartup(true);
bean.afterPropertiesSet();
return (DataSource) bean.getObject();
}
}
This class I put in the web application:
#SpringBootApplication
public class QuarzoApiApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(QuarzoApiApplication.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(applicationClass);
}
private static Class<QuarzoApiApplication> applicationClass = QuarzoApiApplication.class;
}
#RestController
class HelloController {
#Autowired
private IBuserServiceImp buserService;
#RequestMapping("/hello/{name}")
String hello(#PathVariable String name) {
return "Hi ------***--- " + buserService.findAll() + " !";
}
}
pom.xml in the jar file:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>2.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>io.quarzo.web</groupId>
<artifactId>quarzo-domain</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.10.Final</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
<scope>runtime</scope>
</dependency>
</dependencies>
pom.xml of the web application:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.quarzo.web</groupId>
<artifactId>quarzo-service</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>io.quarzo.web</groupId>
<artifactId>quarzo-domain</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
The stacktrace is too large, but I cut the messages:
14:57:54,857 ERROR [org.jboss.as.server] (management-handler-thread - 3) WFLYSRV0014: Replacement of deployment "quarzo-api.war" by deployment "quarzo-api.war" was rolled back with the following failure message:
{
"WFLYCTL0080: Failed services" => {"jboss.deployment.unit.\"quarzo-api.war\".WeldStartService" => "Failed to start service
Caused by: org.jboss.weld.exceptions.DefinitionException: Exception List with 1 exceptions:
Exception 0 :
javax.enterprise.inject.UnsatisfiedResolutionException: Unable to resolve a bean for 'javax.persistence.EntityManager' with qualifiers [#javax.enterprise.inject.Default(), #javax.enterprise.inject.Any()].
at org.springframework.data.jpa.repository.cdi.JpaRepositoryExtension.createRepositoryBean(JpaRepositoryExtension.java:120)
at org.springframework.data.jpa.repository.cdi.JpaRepositoryExtension.afterBeanDiscovery(JpaRepositoryExtension.java:96)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.jboss.weld.injection.StaticMethodInjectionPoint.invoke(StaticMethodInjectionPoint.java:95)
at org.jboss.weld.injection.MethodInvocationStrategy$SpecialParamPlusBeanManagerStrategy.invoke(MethodInvocationStrategy.java:144)
at org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:330)
at org.jboss.weld.event.ExtensionObserverMethodImpl.sendEvent(ExtensionObserverMethodImpl.java:123)
at org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:308)
at org.jboss.weld.event.ObserverMethodImpl.notify(ObserverMethodImpl.java:286)
at org.jboss.weld.util.Observers.notify(Observers.java:172)
at org.jboss.weld.event.ObserverNotifier.notifySyncObservers(ObserverNotifier.java:285)
at org.jboss.weld.event.ObserverNotifier.notify(ObserverNotifier.java:273)
at org.jboss.weld.event.ObserverNotifier.fireEvent(ObserverNotifier.java:177)
at org.jboss.weld.event.ObserverNotifier.fireEvent(ObserverNotifier.java:171)
at org.jboss.weld.bootstrap.events.AbstractContainerEvent.fire(AbstractContainerEvent.java:53)
at org.jboss.weld.bootstrap.events.AbstractDefinitionContainerEvent.fire(AbstractDefinitionContainerEvent.java:44)
at org.jboss.weld.bootstrap.events.AfterBeanDiscoveryImpl.fire(AfterBeanDiscoveryImpl.java:75)
at org.jboss.weld.bootstrap.WeldStartup.deployBeans(WeldStartup.java:456)
at org.jboss.weld.bootstrap.WeldBootstrap.deployBeans(WeldBootstrap.java:86)
at org.jboss.as.weld.WeldStartService.start(WeldStartService.java:96)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1736)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.execute(ServiceControllerImpl.java:1698)
at org.jboss.msc.service.ServiceControllerImpl$ControllerTask.run(ServiceControllerImpl.java:1556)
at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1985)
at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1487)
at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1378)
at java.lang.Thread.run(Thread.java:748)
"},
"WFLYCTL0288: One or more services were unable to start due to one or more indirect dependencies not being available." => {
"Services that were unable to start:" => [
"jboss.deployment.unit.\"quarzo-api.war\".CdiValidatorFactoryService",
"jboss.deployment.unit.\"quarzo-api.war\".component.\"com.sun.faces.config.ConfigureListener\".WeldInstantiator",
"jboss.deployment.unit.\"quarzo-api.war\".component.\"javax.faces.webapp.FacetTag\".WeldInstantiator",
"jboss.deployment.unit.\"quarzo-api.war\".component.\"javax.servlet.jsp.jstl.tlv.PermittedTaglibsTLV\".WeldInstantiator",
"jboss.deployment.unit.\"quarzo-api.war\".component.\"javax.servlet.jsp.jstl.tlv.ScriptFreeTLV\".WeldInstantiator",
"jboss.deployment.unit.\"quarzo-api.war\".component.\"org.jboss.weld.module.web.servlet.WeldInitialListener\".WeldInstantiator",
.
.
.
],
"Services that may be the cause:" => [
"jboss.clustering.web.route.default-server",
"jboss.deployment.unit.\"quarzo-api.war\".component.\"com.sun.faces.config.ConfigureListener\".START",
"jboss.deployment.unit.\"quarzo-api.war\".component.\"com.sun.faces.config.ConfigureListener\".WeldInstantiator",
"jboss.deployment.unit.\"quarzo-api.war\".component.\"javax.faces.webapp.FacetTag\".START",
"jboss.deployment.unit.\"quarzo-api.war\".component.\"javax.faces.webapp.FacetTag\".WeldInstantiator",
"jboss.deployment.unit.\"quarzo-api.war\".component.\"javax.servlet.jsp.jstl.tlv.PermittedTaglibsTLV\".START",
.
.
.
"org.wildfly.clustering.infinispan.cache-container.web",
"org.wildfly.clustering.infinispan.cache-container-configuration.hibernate",
"org.wildfly.clustering.infinispan.cache-container-configuration.hibernate.transport",
"org.wildfly.clustering.infinispan.cache-container-configuration.server",
"org.wildfly.clustering.infinispan.cache-container-configuration.server.transport",
"org.wildfly.clustering.infinispan.cache-container-configuration.web",
"org.wildfly.clustering.infinispan.cache-container-configuration.web.transport",
"org.wildfly.clustering.infinispan.default-cache.ejb",
"org.wildfly.clustering.infinispan.default-cache.web",
"org.wildfly.clustering.infinispan.default-cache-configuration.server",
"org.wildfly.clustering.infinispan.default-cache-configuration.web"
]
}
}
I solved this, the problem was I had a beans.xml in my jar project. I deleted the beans.xml and it works

Spring boot not able to recognize JSP

I have configured Spring Boot using annotations.
I have the following files
1)AppStarter class for configuring spring boot
#Configuration
#EnableAutoConfiguration
#PropertySource(value = "classpath:app.properties", ignoreResourceNotFound = true)
#ComponentScan(basePackages = "com.sample.config")
public class AppStarter extends SpringBootServletInitializer{
#Value("${server.contextPath}")
private String contextPath;
#Value("${server.port:8080}")
private String port;
#Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
#Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory();
factory.setPort(Integer.valueOf(port));
factory.setContextPath(contextPath);
factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notfound.html"));
return factory;
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(AppStarter.class);
}
public static void main(String[] args) {
SpringApplication.run(AppStarter.class, args);
}
}
2)WebConfig class
#Configuration
#ComponentScan(basePackages = {"com.sample.rest"})
#EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter
{
#Bean
public static PropertySourcesPlaceholderConfigurer properties()
{
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
Resource[] resources = new ClassPathResource[]{new ClassPathResource("app.properties")};
configurer.setLocations(resources);
configurer.setIgnoreUnresolvablePlaceholders(true);
return configurer;
}
#Bean
public InternalResourceViewResolver viewResolver()
{
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/pages/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
3)app.properties
core_pool_size = 100
max_pool_size = 600
queue_capacity = 160
server.port=8080
spring.view.prefix: /WEB-INF/pages/
spring.view.suffix: .jsp
4)UserController class
#Controller
public class UserController extends AbstractController {
#RequestMapping(value = "/user/add")
public String user()
{
return "adduser";
}
}
5)pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>1.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>1.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.hateoas</groupId>
<artifactId>spring-hateoas</artifactId>
<version>0.16.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
</dependency>
<dependency>
<groupId>net.sf.dozer</groupId>
<artifactId>dozer</artifactId>
<version>5.5.1</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
<exclusion>
<artifactId>org.slf4j</artifactId>
<groupId>slf4j-log4j12</groupId>
</exclusion>
<exclusion>
<artifactId>log4j</artifactId>
<groupId>log4j</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<scope>provided</scope>
</dependency>
<!--Spring boot test-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>1.2.0.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-jpamodelgen</artifactId>
<version>4.3.7.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java.version}</version>
<scope>runtime</scope>
</dependency>
</dependencies>
6)adduser.jsp which is in webapp/WEB_INF/pages folder
When I try to access my jsp through localhost:8080/sample/user/add i get :
org.springframework.web.servlet.PageNotFound | No mapping found for HTTP request with URI [/sample/WEB-INF/pages/adduser.jsp] in DispatcherServlet with name 'dispatcherServlet'
Can anyone could provide any help on this issue?
You configured: spring.view.prefix: /WEB-INF/jsp/
But your folder is: webapp/WEB_INF/pages
/jsp vs, /pages
You need to change one of them, so that they match!
Second: you need to request the url (That is written at your controller but not the path of the jsp!
So use:
localhost:8080/<yourAppName>/user/add instead of /sample/WEB-INF/pages/adduser.jsp
to use localhost:8080/samples/user/add, you would need to change the controller code to this,
#Controller
#RequestMapping("/samples")
public class UserController extends AbstractController {
#RequestMapping(value = "/user/add")
public String user()
{
return "adduser";
}
}
It looks like you have an embedded Tomcat container configured. JSP pages are not supported when Tomcat is embedded. http://docs.spring.io/spring-boot/docs/1.2.1.RELEASE/reference/htmlsingle/#boot-features-jsp-limitations
Try this:
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}

Spring Boot/Spring Integration Servlet Context/DelegatingWebMvcConfiguration issue

I'm not sure the best way to word this issue, because I have no idea why this happens.
When I start up my Spring Boot application without the spring-integration-core jar, my app starts up fine. The second I add the spring-boot-starter-integration or any spring-integration-core library to my Maven pom file the servlet context is always null on my DelegatingWebMvcConfiguration class and I get the following error:
java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
After doing some debugging, I see the DelegatingWebMvcConfiguration class initialized before the EmbeddedWebApplicationContext sets the servlet context for my application, which makes sense why the servlet context is null for my DelegatingWebMvcConfiguration and set for all the other classes initialized with postProcessBeforeInitialization in ServletContextAwareProcessor. Simply removing the Spring Integration dependency fixes the issue, but I'd like to use Spring Integration in my Boot application.
My question is what would cause the DelegatingWebMvcConfiguration to be created before the EmbeddedWebApplicationContext can call prepareEmbeddedWebApplicationContext method.
Spring dependencies using Spring Boot 1.1.8.RELEASE:
org.springframework.boot
spring-boot-starter-web
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</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-data-solr</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-integration</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.hateoas</groupId>
<artifactId>spring-hateoas</artifactId>
<version>0.16.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-core</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-cassandra</artifactId>
<version>1.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.ldap</groupId>
<artifactId>spring-ldap-core</artifactId>
<version>2.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>4.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
<version>4.1.2.RELEASE</version>
</dependency>
My root configuration file:
#Configuration
#EnableAutoConfiguration
#EnableAsync
#EnableEntityLinks
#EnableSpringDataWebSupport
#ComponentScan
#PropertySource(value = "file:../application.properties",
ignoreResourceNotFound = true)
public class ApplicationInitializer extends SpringBootServletInitializer
implements EmbeddedServletContainerCustomizer {
public static void main(String[] args) throws Exception {
SpringApplication.run(ApplicationInitializer.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application){
return application.sources(ApplicationInitializer.class);
}
#Override
public void customize(ConfigurableEmbeddedServletContainer container) {
container.setContextPath(APPLICATION_ROOT_PATH);
}
// Global beans defined here
}
Update: After trying many different things, I found out after disabling my SchedulingConfigurer my app now starts. Here is my SchedulingConfigurer
#Configuration
#EnableScheduling
#EnableConfigurationProperties(SchedulingProperties.class)
public class SchedulingConfig implements SchedulingConfigurer {
//Inject Runnables and properties
#Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(taskScheduler());
// call taskRegistrar.addFixedRateTask with runnable and property rate value
}
#Bean(destroyMethod = "shutdown")
public Executor taskScheduler() {
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.setPoolSize(Runtime.getRuntime().availableProcessors());
return taskScheduler;
}
}

Resources