Spring Boot controller required a bean of type 'org.dozer.Mapper' that could not be found - spring-boot

I've created a spring boot project and added
compile('net.sf.dozer:dozer:5.5.1')
to dependencies. But the class, org.dozer.Mapper, is not recognized by my app.
I run gradle clean, gradle buildDependents and gradle build.
But things did not changed.
What should I do ?
my build.gradle
buildscript {
ext {
springBootVersion = '2.0.0.RC1'
}
repositories {
mavenCentral()
maven { url "https://repo.spring.io/snapshot" }
maven { url "https://repo.spring.io/milestone" }
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
group = 'com.everglowtrading'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
maven { url "https://repo.spring.io/snapshot" }
maven { url "https://repo.spring.io/milestone" }
maven { url "https://repository.jboss.org/nexus/content/repositories/releases" }
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-aop')
compile('org.flywaydb:flyway-core')
compile('org.springframework.boot:spring-boot-starter-hateoas')
compile('org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.1')
compile('org.springframework.boot:spring-boot-starter-thymeleaf')
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.springframework.boot:spring-boot-starter-webflux')
compile('org.springframework.data:spring-data-commons')
compile('com.h2database:h2')
compile('net.sf.dozer:dozer:5.5.1')
runtime('org.springframework.boot:spring-boot-devtools')
runtime('com.h2database:h2')
compileOnly('org.projectlombok:lombok')
testCompile('org.springframework.boot:spring-boot-starter-test')
testCompile('io.projectreactor:reactor-test')
}
The controller
package com.myproject.stock.controllers;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import javax.servlet.http.HttpServletResponse;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.myproject.stock.domain.model.Stock;
import com.myproject.stock.domain.repository.StockCriteria;
import com.myproject.stock.form.StockListForm;
import com.myproject.stock.service.StockService;
#RestController
public class StockController {
private static final int DEFAULT_PAGEABLE_SIZE = 5;
#Autowired
Mapper beanMapper;
#Autowired
StockService<Integer> stockService;
#Autowired
MessageSource msg;
#RequestMapping("/")
void index(HttpServletResponse response) throws IOException {
response.sendRedirect("/stock");
}
#RequestMapping("/stock")
public ModelAndView stock(ModelAndView mav) {
Stock stock = stockService.getItems(11);
List<Stock> stockList = stockService.getAllItems();
String message = msg.getMessage("stock.label", null, Locale.JAPAN);
mav.addObject("stock_id", stock.getId());
mav.addObject("stockList", stockList);
mav.addObject("message", message);
mav.addObject("stockBuildingName", stock.getBuilding_name());
mav.setViewName("stock/search/index");
return mav;
}
#RequestMapping("/stock/search")
public String index(#Validated StockListForm stockListForm
, BindingResult bindingResult
, Pageable pageable
, Model model) {
StockCriteria criteria = beanMapper.map(stockListForm, StockCriteria.class);
Page<Stock> page = stockService.findPageByCriteria(criteria, pageable);
model.addAttribute("page", page);
return "stock/search/index";
}
}
the error message
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.0.0.RC1)
2018-02-19 22:15:35.648 INFO 7950 --- [ restartedMain] c.e.wms.stock.WmsApplication : Starting WmsApplication on YatabeMBP.local with PID 7950 (/Users/ayatabe/dev/wms-stock/build/classes/java/main started by ayatabe in /Users/ayatabe/dev/wms-stock)
2018-02-19 22:15:35.648 INFO 7950 --- [ restartedMain] c.e.wms.stock.WmsApplication : No active profile set, falling back to default profiles: default
2018-02-19 22:15:35.695 INFO 7950 --- [ restartedMain] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext#82f0a7d: startup date [Mon Feb 19 22:15:35 JST 2018]; root of context hierarchy
2018-02-19 22:15:36.772 INFO 7950 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$d86c709b] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-02-19 22:15:37.104 INFO 7950 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 9090 (http)
2018-02-19 22:15:37.114 INFO 7950 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-02-19 22:15:37.114 INFO 7950 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.27
2018-02-19 22:15:37.127 INFO 7950 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/Users/ayatabe/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.]
2018-02-19 22:15:37.209 INFO 7950 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-02-19 22:15:37.209 INFO 7950 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1517 ms
2018-02-19 22:15:37.369 INFO 7950 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
2018-02-19 22:15:37.371 INFO 7950 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet webServlet mapped to [/h2console/*]
2018-02-19 22:15:37.374 INFO 7950 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-02-19 22:15:37.374 INFO 7950 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-02-19 22:15:37.374 INFO 7950 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-02-19 22:15:37.374 INFO 7950 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-02-19 22:15:37.415 WARN 7950 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'stockController': Unsatisfied dependency expressed through field 'beanMapper'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.dozer.Mapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
2018-02-19 22:15:37.417 INFO 7950 --- [ restartedMain] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2018-02-19 22:15:37.434 INFO 7950 --- [ restartedMain] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-02-19 22:15:37.550 ERROR 7950 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Field beanMapper in com.myproject.stock.controllers.StockController required a bean of type 'org.dozer.Mapper' that could not be found.
Action:
Consider defining a bean of type 'org.dozer.Mapper' in your configuration.

You haven't define a bean for org.dozer.Mapper type so Spring can't inject a proper instance to your controller class.
The simplest way to define this bean is to add following method to your main Spring application class:
#Bean
public Mapper mapper() {
return new DozerBeanMapper();
}
Alternatively you can put it in any #Configuration annotated class.

For those who might run into the same problem as me:
Add #MapperScan("yourMapperPath") at your spring boot main launch class. If the notation shows as red, reimport your mybatis-spring-boot-starter dependency:
Go to your project pom.xml > right click on the artifactId > Maven > Reimport
I thought I have imported the dependency days ago, but the project didn't.

Related

Spring Cloud Kubernetes - Spring boot fails to start when config reload is enabled

I have this demo project which prints a label that is read from the configurations.
This is my main class:
#SpringBootApplication
#EnableDiscoveryClient
#RestController
public class DemoApplication {
private MyConfig config;
private DiscoveryClient discoveryClient;
#Autowired
public DemoApplication(MyConfig config, DiscoveryClient discoveryClient) {
this.config = config;
this.discoveryClient = discoveryClient;
}
#RequestMapping("/")
public String info() {
return config.getMessage();
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#RequestMapping("/services")
public String services() {
StringBuilder b = new StringBuilder();
discoveryClient.getServices().forEach((s) -> b.append(s).append(" , "));
return b.toString();
}
}
And the MyConfig class is:
#Configuration
#ConfigurationProperties(prefix = "bean")
public class MyConfig {
private String message = "a message that can be changed live";
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
The bootstrap.properties contain:
spring.application.name=demo
spring.cloud.kubernetes.config.name=demo
spring.cloud.kubernetes.config.enabled=true
spring.cloud.kubernetes.config.namespace=default
spring.cloud.kubernetes.reload.enabled=true
spring.cloud.kubernetes.reload.monitoring-config-maps=true
spring.cloud.kubernetes.reload.strategy=refresh
spring.cloud.kubernetes.reload.mode=event
management.endpoint.refresh.enabled=true
management.endpoints.web.exposure.include=*
And the dependencies in build.gradle:
dependencies {
compile("org.springframework.boot:spring-boot-starter-web")
compile("org.springframework.boot:spring-boot-starter-actuator")
compile("org.springframework.cloud:spring-cloud-starter-kubernetes:+")
compile("org.springframework.cloud:spring-cloud-starter-kubernetes-config:+")
testCompile('org.springframework.boot:spring-boot-starter-test')
runtime("org.springframework.boot:spring-boot-properties-migrator")
}
I'm creating the ConfigMap with kubectl create -f configmap-demo.yml being the content:
apiVersion: v1
kind: ConfigMap
metadata:
name: demo
data:
bean.message: This is an info from k8
When deploying in Kubernetes I get the following error on Spring Boot startup:
2019-01-02 13:41:41.462 INFO 1 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'configurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$e13002af] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.1.RELEASE)
2019-01-02 13:41:41.940 INFO 1 --- [ main] b.c.PropertySourceBootstrapConfiguration : Located property source: ConfigMapPropertySource {name='configmap.demo.default'}
2019-01-02 13:41:41.942 INFO 1 --- [ main] b.c.PropertySourceBootstrapConfiguration : Located property source: SecretsPropertySource {name='secrets.demo.default'}
2019-01-02 13:41:42.030 INFO 1 --- [ main] com.example.demo.DemoApplication : The following profiles are active: kubernetes
2019-01-02 13:41:43.391 INFO 1 --- [ main] o.s.cloud.context.scope.GenericScope : BeanFactory id=416ee750-8ebb-365d-9114-12b51acaa1e0
2019-01-02 13:41:43.490 INFO 1 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$e13002af] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-01-02 13:41:43.917 INFO 1 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2019-01-02 13:41:43.952 INFO 1 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-01-02 13:41:43.953 INFO 1 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/9.0.13
2019-01-02 13:41:43.969 INFO 1 --- [ main] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/usr/lib/jvm/java-1.8-openjdk/jre/lib/amd64/server:/usr/lib/jvm/java-1.8-openjdk/jre/lib/amd64:/usr/lib/jvm/java-1.8-openjdk/jre/../lib/amd64:/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib]
2019-01-02 13:41:44.156 INFO 1 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-01-02 13:41:44.157 INFO 1 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2033 ms
2019-01-02 13:41:44.957 INFO 1 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2019-01-02 13:41:45.353 WARN 1 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'propertyChangeWatcher' defined in class path resource [org/springframework/cloud/kubernetes/config/reload/ConfigReloadAutoConfiguration$ConfigReloadAutoConfigurationBeans.class]: Unsatisfied dependency expressed through method 'propertyChangeWatcher' parameter 1; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'configurationUpdateStrategy' defined in class path resource [org/springframework/cloud/kubernetes/config/reload/ConfigReloadAutoConfiguration$ConfigReloadAutoConfigurationBeans.class]: Unsatisfied dependency expressed through method 'configurationUpdateStrategy' parameter 2; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.cloud.context.restart.RestartEndpoint' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
2019-01-02 13:41:45.358 INFO 1 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
2019-01-02 13:41:45.370 INFO 1 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2019-01-02 13:41:45.398 INFO 1 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-01-02 13:41:45.612 ERROR 1 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 2 of method configurationUpdateStrategy in org.springframework.cloud.kubernetes.config.reload.ConfigReloadAutoConfiguration$ConfigReloadAutoConfigurationBeans required a bean of type 'org.springframework.cloud.context.restart.RestartEndpoint' that could not be found.
The following candidates were found but could not be injected:
- Bean method 'restartEndpoint' in 'RestartEndpointWithIntegrationConfiguration' not loaded because #ConditionalOnClass did not find required class 'org.springframework.integration.monitor.IntegrationMBeanExporter'
- Bean method 'restartEndpointWithoutIntegration' in 'RestartEndpointWithoutIntegrationConfiguration' not loaded because #ConditionalOnEnabledEndpoint no property management.endpoint.restart.enabled found so using endpoint default
Action:
Consider revisiting the entries above or defining a bean of type 'org.springframework.cloud.context.restart.RestartEndpoint' in your configuration.
If I set spring.cloud.kubernetes.reload.enabled to false everything works and the configmap is read and put to use. Now my goal is to reload the configuration if the configmap changes but get the exception seen above. I can invoke /actuator/refresh manually so I don't think it is the lack of the availability for the refresh endpoint.
I created a demo project with all included at https://drive.google.com/open?id=1QbP8vePALLZ2hWQJArnyxrzSySuXHKiz .
It starts if you set management.endpoint.restart.enabled=true
The message tells you that it can't load a RestartEndpoint bean. None was created because there's two ways it could be loaded and nether was satisfied:
Bean method 'restartEndpoint' in 'RestartEndpointWithIntegrationConfiguration' not loaded because #ConditionalOnClass did not find required class 'org.springframework.integration.monitor.IntegrationMBeanExporter'
Well you're not using spring integration so I guess you don't want this path - you want the other one.
Bean method 'restartEndpointWithoutIntegration' in 'RestartEndpointWithoutIntegrationConfiguration' not loaded because #ConditionalOnEnabledEndpoint no property management.endpoint.restart.enabled found so using endpoint default
So we need to set management.endpoint.restart.enabled=true, which is also set in the official reload example project. Without setting this the RestartEndpoint bean that we require will not be loaded.
In the application.properties add these two lines:
management.endpoint.restart.enabled=true
spring.jmx.enabled=true

Spring Boot Oauth2 oauth/token not mapped on initialization

I am applying OAuth2 security to my Spring Boot Application.
My issue is that when I run the application /oauth/token path is not mapped at the time of application initialization.
AuthorizationServerConfig.java
package com.example.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
#Configuration
#EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
#Autowired
private AuthenticationManager authenticationManager;
#Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenthicated()");
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory().withClient("clientid")
.secret("secret")
.authorizedGrantTypes("authorization_code")
.scopes("user_info")
.autoApprove(true);
}
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
}
}
ResourceServerConfig.java
package com.example.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
#EnableResourceServer
#Configuration
public class ResourceServerConfig extends WebSecurityConfigurerAdapter {
#Autowired
private AuthenticationManager authenticationManager;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.requestMatchers().antMatchers("/").and().authorizeRequests().anyRequest().authenticated();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.parentAuthenticationManager(authenticationManager)
.inMemoryAuthentication().withUser("admin")
.password("admin")
.roles("ADMIN");
}
}
ProductRestController.java
#RestController
#RequestMapping("/product")
public class ProductRestController {
#RequestMapping(value = "/{id}", method = RequestMethod.GET)
#ResponseBody
public String getProductById(#PathVariable("id") int id) {
System.out.println("In Controller");
return "Hello";
}
Application Console Log:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.7.RELEASE)
2017-09-22 11:40:51.155 INFO 10744 --- [ restartedMain] c.o.inventory.launch.Application : Starting Application on Twinkle-PC with PID 10744 (D:\OrderhiveSpring\orderhive-inventory\bin started by Twinkle in D:\OrderhiveSpring\orderhive-inventory)
2017-09-22 11:40:51.155 INFO 10744 --- [ restartedMain] c.o.inventory.launch.Application : No active profile set, falling back to default profiles: default
2017-09-22 11:40:51.155 INFO 10744 --- [ restartedMain] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#9cbf79e: startup date [Fri Sep 22 11:40:51 UTC 2017]; root of context hierarchy
2017-09-22 11:40:52.050 INFO 10744 --- [ restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8888 (http)
2017-09-22 11:40:52.050 INFO 10744 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2017-09-22 11:40:52.051 INFO 10744 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.20
2017-09-22 11:40:52.063 INFO 10744 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2017-09-22 11:40:52.064 INFO 10744 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 909 ms
2017-09-22 11:40:52.124 INFO 10744 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-09-22 11:40:52.124 INFO 10744 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-09-22 11:40:52.124 INFO 10744 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-09-22 11:40:52.124 INFO 10744 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2017-09-22 11:40:52.124 INFO 10744 --- [ost-startStop-1] .s.DelegatingFilterProxyRegistrationBean : Mapping filter: 'springSecurityFilterChain' to: [/*]
2017-09-22 11:40:52.124 INFO 10744 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2017-09-22 11:40:58.354 INFO 10744 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2017-09-22 11:40:58.355 INFO 10744 --- [ restartedMain] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2017-09-22 11:40:58.362 INFO 10744 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2017-09-22 11:40:58.592 INFO 10744 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2017-09-22 11:40:58.856 INFO 10744 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#9cbf79e: startup date [Fri Sep 22 11:40:51 UTC 2017]; root of context hierarchy
2017-09-22 11:40:58.871 INFO 10744 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/product/{id}],methods=[GET]}" onto public java.lang.String com.orderhive.inventory.controller.ProductRestController.getProductById(int)
2017-09-22 11:40:58.871 INFO 10744 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-09-22 11:40:58.871 INFO 10744 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-09-22 11:40:58.887 INFO 10744 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-09-22 11:40:58.887 INFO 10744 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-09-22 11:40:58.902 INFO 10744 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-09-22 11:40:58.949 INFO 10744 --- [ restartedMain] b.a.s.AuthenticationManagerConfiguration :
Using default security password: a1f8d8ad-e937-4dd6-8be2-2648a9ed9a80
2017-09-22 11:40:58.964 INFO 10744 --- [ restartedMain] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: OrRequestMatcher [requestMatchers=[Ant [pattern='/css/**'], Ant [pattern='/js/**'], Ant [pattern='/images/**'], Ant [pattern='/webjars/**'], Ant [pattern='/**/favicon.ico'], Ant [pattern='/error']]], []
2017-09-22 11:40:58.964 INFO 10744 --- [ restartedMain] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: OrRequestMatcher [requestMatchers=[Ant [pattern='/**']]], [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#6a1033a9, org.springframework.security.web.context.SecurityContextPersistenceFilter#35d7fa68, org.springframework.security.web.header.HeaderWriterFilter#7d6e8d02, org.springframework.security.web.authentication.logout.LogoutFilter#e859232, org.springframework.security.web.authentication.www.BasicAuthenticationFilter#40b3d30, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#57b0571b, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#5e3fd672, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#48992772, org.springframework.security.web.session.SessionManagementFilter#69c735a2, org.springframework.security.web.access.ExceptionTranslationFilter#723216e7, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#e7327d0]
2017-09-22 11:40:59.002 INFO 10744 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2017-09-22 11:40:59.042 INFO 10744 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2017-09-22 11:40:59.054 INFO 10744 --- [ restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8888 (http)
2017-09-22 11:40:59.056 INFO 10744 --- [ restartedMain] c.o.inventory.launch.Application : Started Application in 7.936 seconds (JVM running for 1520.559)
In this log, GET /product/id is mapped but POST /oauth/token or any of the OAuth paths are not mapped and hence it gives a 404 not found error.
I have uploaded the configurations,let me know if any config is missing for OAuth2 security.
I think you are missing WebMvcConfigurerAdapter implementation, I have implemented the same Ouath2 applications using same technologies like spring boot. You can verify your config files, GitHub links are here-
https://github.com/manishsingh27/TokenBasedAuth/blob/main/authz/src/main/java/com/adms/authz/config/WebConfiguration.java
https://github.com/manishsingh27/TokenBasedAuth/blob/main/authz/src/main/java/com/adms/authz/config/AuthorizationConfiguration.java

cannot find DiscoveryClient bean error in spring boot

2017-03-16 16:09:08.821 INFO 9104 --- [ main] com.hello.EurekaClientApplication : No active profile set, falling back to default profiles: default
2017-03-16 16:09:08.848 INFO 9104 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#5dcd8c7a: startup date [Thu Mar 16 16:09:08 CDT 2017]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext#441772e
2017-03-16 16:09:09.873 INFO 9104 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'hystrixFeature' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.cloud.netflix.hystrix.HystrixCircuitBreakerConfiguration$HystrixWebConfiguration; factoryMethodName=hystrixFeature; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/cloud/netflix/hystrix/HystrixCircuitBreakerConfiguration$HystrixWebConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.cloud.netflix.hystrix.HystrixCircuitBreakerConfiguration; factoryMethodName=hystrixFeature; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/cloud/netflix/hystrix/HystrixCircuitBreakerConfiguration.class]]
2017-03-16 16:09:10.364 WARN 9104 --- [ main] o.s.c.a.ConfigurationClassPostProcessor : Cannot enhance #Configuration bean definition 'refreshScope' since its singleton instance has been created too early. The typical cause is a non-static #Bean method with a BeanDefinitionRegistryPostProcessor return type: Consider declaring such methods as 'static'.
2017-03-16 16:09:10.701 INFO 9104 --- [ main] o.s.cloud.context.scope.GenericScope : BeanFactory id=d0eb8cfd-bd5b-3565-9f63-f671e896f6be
2017-03-16 16:09:10.736 INFO 9104 --- [ main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2017-03-16 16:09:11.312 INFO 9104 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$94394ff6] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-03-16 16:09:12.091 INFO 9104 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-03-16 16:09:12.128 INFO 9104 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
2017-03-16 16:09:12.130 INFO 9104 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.11
2017-03-16 16:09:12.546 INFO 9104 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2017-03-16 16:09:12.547 INFO 9104 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 3699 ms
2017-03-16 16:09:13.191 INFO 9104 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'proxyStreamServlet' to [/proxy.stream]
2017-03-16 16:09:13.193 INFO 9104 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2017-03-16 16:09:13.198 INFO 9104 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'metricsFilter' to: [/*]
2017-03-16 16:09:13.199 INFO 9104 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-03-16 16:09:13.199 INFO 9104 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-03-16 16:09:13.200 INFO 9104 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-03-16 16:09:13.200 INFO 9104 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2017-03-16 16:09:13.200 INFO 9104 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'webRequestLoggingFilter' to: [/*]
2017-03-16 16:09:13.200 INFO 9104 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'applicationContextIdFilter' to: [/*]
2017-03-16 16:09:13.269 WARN 9104 --- [ main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'eurekaClientApplication': Unsatisfied dependency expressed through field 'clientservice'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'clientService' defined in file [C:\Users\Mike\workspace\Eureka_client\target\classes\com\hello\ClientService.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.netflix.discovery.DiscoveryClient' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
2017-03-16 16:09:13.306 INFO 9104 --- [ main] o.apache.catalina.core.StandardService : Stopping service Tomcat
2017-03-16 16:09:13.404 INFO 9104 --- [ main] utoConfigurationReportLoggingInitializer :
Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-03-16 16:09:13.745 ERROR 9104 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in com.hello.ClientService required a bean of type 'com.netflix.discovery.DiscoveryClient' that could not be found.
Action:
Consider defining a bean of type 'com.netflix.discovery.DiscoveryClient' in your configuration.
package com.hello;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.stereotype.Service;
import com.netflix.discovery.DiscoveryClient;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
#EnableDiscoveryClient
#Service
public class ClientService {
private final DiscoveryClient disc;
public ClientService(DiscoveryClient disc){
this.disc=disc;
}
#HystrixCommand(fallbackMethod="disp")
public String serviceInstancesByApplicationName(){
return this.disc.getInstancesById("a-bootiful-client").toString();
}
public String disp(){
return "This is fall back method";
}
}
package com.hello;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
#EnableHystrix
#EnableHystrixDashboard
#EnableDiscoveryClient
#SpringBootConfiguration
#EnableAutoConfiguration
#ComponentScan
#RestController
public class EurekaClientApplication {
#Autowired
private ClientService clientservice;
public static void main(String[] args) {
SpringApplication.run(EurekaClientApplication.class, args);
}
#RequestMapping("/serv")
public String serviceInstancesByApplicationName(){
return clientservice.serviceInstancesByApplicationName();
}
}
i am trying to create a simple eureka service and client program and enable hystrix on that. but i am getting this error on the code
You imported wrong DiscoveryClient class in your code. DiscoveryClient from netflix is not provided as Spring Bean. So you should use one from spring-cloud.
Try to import org.springframework.cloud.client.discovery.DiscoveryClient instead of com.netflix.discovery.DiscoveryClient in your ClientService class.
Also you need to change this.disc.getInstancesById("a-bootiful-client") to this.disc.getInstances(...).
This would be because of 2 cases.
1: The first situation is whether the imported package does not match
If you used #EnableDiscoveryClient
import org.springframework.cloud.client.discovery.DiscoveryClient
"instead of "
com.netflix.discovery.DiscoveryClient
If you used #EnableEurekaClient use this below import
import org.springframework.cloud.netflix.eureka.EnableEurekaClient
2: I did not select the starer-web dependency when I created the module, have added this below dependency in pom.xml and rebuild the project to fetch the added dependency.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Use com.netflix.discovery.EurekaClient instead of com.netflix.discovery.DiscoveryClient. This is the discovery client provided by Netflix.
If you want to use spring discovery client then use org.springframework.cloud.client.discovery.DiscoveryClient as suggested by #yongsung.yoon
I've also faced with the same issue, I solved it after adding spring boot-starter-web dependency

AspectJ LTW not working with Spring Boot on unmanaged classes

I'm facing a problem on a large scale application using SpringBoot and AspectJ for logging purposes. The logging works fine for Spring Beans, but does not work for unmanaged classes (the ones I instantiate with 'new').
I've created a sample app where you can see the problem happening, you can access it here:
https://bitbucket.org/tomkro/stack_question
The application is pretty simple, the Gradle file is a common with the standard Spring Boot starters.
There are 5 relevant classes here.
Application.java, which is the main class:
#EnableAspectJAutoProxy
#EnableLoadTimeWeaving(aspectjWeaving= EnableLoadTimeWeaving.AspectJWeaving.ENABLED)
#SpringBootApplication(scanBasePackages = "com.test.*")
public class Application {
public static void main(final String[] args) {
SpringApplication.run(Application.class, args);
}
}
The AspectConfig file (which for the sake of simplicity also defines the RestController, could be easily separated files)
#RestController
#Configuration
#ComponentScan(basePackages = {"com.test"})
public class AspectConfig {
#Bean
public TestLogger testLogger(){
return new TestLogger();
}
#Autowired
TestClass testClass;
#RequestMapping("/")
public int get() {
return testClass.methodFromClass1();
}
}
The TestLogger, which defines the aspect for this app:
#Aspect
public class TestLogger {
public TestLogger() {
}
#Around("execution( * com.test.classes..*.*(..))")
public Object aroundExecution(ProceedingJoinPoint pjp) throws Throwable {
String packageName = pjp.getSignature().getDeclaringTypeName();
String methodName = pjp.getSignature().getName();
long start = System.currentTimeMillis();
System.out.println(packageName + "." + methodName + " - Starting execution ");
Object output = pjp.proceed();
Long elapsedTime = System.currentTimeMillis() - start;
System.out.println(packageName + "." + methodName + " - Ending execution ["+elapsedTime+" ms]");
return output;
}
}
And then there's two files, one managed by Spring, the other not:
TestClass1:
#Component
public class TestClass {
public int methodFromClass1() {
TestClass2 test = new TestClass2();
return test.methodFromClass2();
}
}
TestClass2
public class TestClass2 {
public int methodFromClass2() {
int a = 10;
int b = 5;
return b + a;
}
}
Also there's the aop.xml file in META-INF which specifies the Aspect
<!DOCTYPE aspectj PUBLIC "-//AspectJ//DTD//EN" "http://www.eclipse.org/aspectj/dtd/aspectj.dtd">
<aspectj>
<weaver option="-debug">
<!-- only weave classes in our application-specific packages -->
<include within="com.test.*"/>
</weaver>
<aspects>
<!-- weave in just this aspect -->
<aspect name="com.test.utilities.TestLogger"/>
</aspects>
</aspectj>
I followed most of this build using the tutorial on the Spring documentation here , and I've been scratching my head for two days now and I can't figure out what's happening. The managed Bean logs fine, but the unmanaged one is not being logged.
I'm using the run.bat included in the project for starting, basically it does this:
call gradle build
java -javaagent:.\src\main\resources\aspectjweaver.jar -javaagent:.\src\main\resources\spring-instrument.jar -jar build\libs\Test-0.0.1-SNAPSHOT.jar
Both jars are the latest. Usually you only would need of the JAR's, but I saw someone using both and gave it a shot. This is the output after startup and execution of a call to "localhost:8080"
[LaunchedURLClassLoader#6d8a00e3] warning javax.* types are not being woven because the weaver option '-Xset:weaveJavaxPackages=true' has not been specified
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.3.0.RELEASE)
2016-04-08 15:21:44.116 INFO 20400 --- [ main] com.test.Application : Starting Application on PC000BR23205 with PID 20400 (C:\git\Test\build\libs\Test-0.0.1-SNAPSHOT.jar started by tkroth in C:\git\T
est)
2016-04-08 15:21:44.120 INFO 20400 --- [ main] com.test.Application : No profiles are active
2016-04-08 15:21:44.294 INFO 20400 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#2cd72cea: startup date [Fri Ap
r 08 15:21:44 BRT 2016]; root of context hierarchy
2016-04-08 15:21:44.950 INFO 20400 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'beanNameViewResolver' with a different definition: replacing [Root bean: class [null]; scope
=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration; fa
ctoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration.class]]
with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$W
ebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAut
oConfigurationAdapter.class]]
2016-04-08 15:21:45.872 INFO 20400 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2016-04-08 15:21:45.888 INFO 20400 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
2016-04-08 15:21:45.891 INFO 20400 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.0.28
2016-04-08 15:21:45.987 INFO 20400 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2016-04-08 15:21:45.987 INFO 20400 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1695 ms
2016-04-08 15:21:46.342 INFO 20400 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2016-04-08 15:21:46.347 INFO 20400 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2016-04-08 15:21:46.348 INFO 20400 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2016-04-08 15:21:46.349 INFO 20400 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2016-04-08 15:21:46.349 INFO 20400 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2016-04-08 15:21:46.439 INFO 20400 --- [ main] o.s.c.w.DefaultContextLoadTimeWeaver : Found Spring's JVM agent for instrumentation
2016-04-08 15:21:46.455 INFO 20400 --- [ main] o.s.c.w.DefaultContextLoadTimeWeaver : Found Spring's JVM agent for instrumentation
[LaunchedURLClassLoader#6d8a00e3] warning javax.* types are not being woven because the weaver option '-Xset:weaveJavaxPackages=true' has not been specified
2016-04-08 15:21:46.781 INFO 20400 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#2cd72cea:
startup date [Fri Apr 08 15:21:44 BRT 2016]; root of context hierarchy
2016-04-08 15:21:46.874 INFO 20400 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto public int com.test.configuration.AspectConfig.get()
2016-04-08 15:21:46.877 INFO 20400 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.sp
ringframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2016-04-08 15:21:46.878 INFO 20400 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoco
nfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest)
2016-04-08 15:21:46.912 INFO 20400 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-04-08 15:21:46.912 INFO 20400 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-04-08 15:21:47.030 INFO 20400 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler
]
2016-04-08 15:21:47.133 INFO 20400 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2016-04-08 15:21:47.204 INFO 20400 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2016-04-08 15:21:47.210 INFO 20400 --- [ main] com.test.Application : Started Application in 3.481 seconds (JVM running for 4.306)
2016-04-08 15:21:51.680 INFO 20400 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2016-04-08 15:21:51.680 INFO 20400 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2016-04-08 15:21:51.704 INFO 20400 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 23 ms
com.test.classes.TestClass.methodFromClass1 - Starting execution
com.test.classes.TestClass.methodFromClass1 - Ending execution [15 ms]
As you can see, TestClass2 is never logged, although it's called. What am I missing here?
The real question is, how can I make non-beans to be handled by LTW in a SpringBoot environment? Feel free to commit changes on the repository I provided above.

Spring boot restful web service staandalone app startup time very slow

When running my restful web service using spring boot as a standalone application, if I run it as a JAR the JVM hangs during startup for around 4-5 minutes (there is no output to console, no Spring Boot Symbol for a long time initially). The entire application takes around 26 minutest to load. If I run the application from Eclipse or package it as war and deploy it, the entire startup time is under 20 seconds.. I can't figure out what the problem is. Followed the instructions in https://spring.io/guides/gs/rest-service/
If I create the exact same spring demo application (greeting etc.) as per the link above the JVM takes around a minute to show the Spring Boot symbol. After that the application starts to load at super slow rate. Final line that I get from this simple application is:
2016-03-10 14:39:58.336 INFO 10344 --- [main] com.deepak.springbootrest.Application : Started Application in 204.826 seconds (JVM running for 254.923)
Startup time is fine when I run it from Eclipse. In eclipse, i see: 2016-03-10 14:56:56.019 INFO 24368 --- [ main] com.deepak.springbootrest.Application : Started Application in 3.452 seconds (JVM running for 4.426)
I am using JDK 1.7, which I assume should be fine.
EDIT: Application startup crawls with: C:\dev\sw\jdk\jdk1.7.0_45\bin\java.exe -Dfile.encoding=UTF-8 -jar target\spring-boot-rest-0.0.1-SNAPSHOT.jar
If I put what eclipse is using on the command line:
C:\dev\sw\jdk\jdk1.7.0_45\bin\java.exe -Dfile.encoding=UTF-8 -classpath C:\dev\bak\files\personal\train\code\tools\spring-boot-rest\target\classes;C:\Users\abrahd2.m2\repository\org\springframework\boot\spring-boot-starter-web\1.3.3.RELEASE\spring-boot-starter-web-1.3.3.RELEASE.jar;........OMITTED.....C:\Users\abrahd2.m2\repository\org\springframework\spring-expression\4.2.5.RELEASE\spring-expression-4.2.5.RELEASE.jar com.deepak.springbootrest.Application
it starts in under 4 seconds
The output from the slow-mo startup log is:
*. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.3.3.RELEASE)
2016-03-10 15:23:19.061 INFO 25576 --- [ main] com.deepak.springbootrest.Application : Starting Application v0.0.1-SNAPSHOT on INENABRAHD2L2C with PID 25576 (C:\dev\bak\files\personal\train\code\tools\spring-boot-rest\target\spring-boot-rest-0.0.1-SNAPSHOT.jar started by abrahd2 in C:\dev\bak\files\personal\train\code\tools\spring-boot-rest)
2016-03-10 15:23:19.625 INFO 25576 --- [ main] com.deepak.springbootrest.Application : No active profile set, falling back to default profiles: default
2016-03-10 15:23:25.529 INFO 25576 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#f1a0fad: startup date [Thu Mar 10 15:23:25 IST 2016]; root of context hierarchy
2016-03-10 15:24:14.317 INFO 25576 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'beanNameViewResolver' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]]
2016-03-10 15:25:15.962 INFO 25576 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2016-03-10 15:25:17.014 INFO 25576 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
2016-03-10 15:25:17.198 INFO 25576 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.0.32
2016-03-10 15:25:25.059 INFO 25576 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2016-03-10 15:25:25.060 INFO 25576 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 119533 ms
2016-03-10 15:25:33.350 INFO 25576 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2016-03-10 15:25:33.721 INFO 25576 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2016-03-10 15:25:33.721 INFO 25576 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2016-03-10 15:25:33.721 INFO 25576 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2016-03-10 15:25:33.721 INFO 25576 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2016-03-10 15:25:49.180 INFO 25576 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#f1a0fad: startup date [Thu Mar 10 15:23:25 IST 2016]; root of context hierarchy
2016-03-10 15:25:59.257 INFO 25576 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/greeting]}" onto public com.deepak.springbootrest.Greeting com.deepak.springbootrest.GreetingController.greeting(java.lang.String)
2016-03-10 15:25:59.352 INFO 25576 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2016-03-10 15:25:59.352 INFO 25576 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2016-03-10 15:25:59.864 INFO 25576 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-03-10 15:25:59.864 INFO 25576 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-03-10 15:26:01.305 INFO 25576 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-03-10 15:26:05.504 INFO 25576 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2016-03-10 15:26:10.089 INFO 25576 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2016-03-10 15:26:10.552 INFO 25576 --- [ main] com.deepak.springbootrest.Application : Started Application in 208.006 seconds (JVM running for 258.259)*
Adding code and pom, which is what is there in the spring guide:
package com.deepak.springbootrest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Run with mvn spring-boot:run or java -jar target/<name of jar> Run with
* http://localhost:8080/greeting
*
* #author abrahd2
*
*/
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
package com.deepak.springbootrest;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
#RequestMapping("/greeting")
public Greeting greeting(#RequestParam(value="name", defaultValue="World") String name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
}
package com.deepak.springbootrest;
public class Greeting {
private final long id;
private final String content;
public Greeting(long id, String content) {
this.id = id;
this.content = content;
}
public long getId() {
return id;
}
public String getContent() {
return content;
}
}
Pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.3.RELEASE</version>
</parent>
<groupId>com.deepak.test</groupId>
<artifactId>spring-boot-rest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Spring boot rest api</name>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<properties>
<java.version>1.7</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

Resources