This question is already asked and i have checked all the solutions, but nothing helped me, am still facing the same issue.
I have configured My Google Appengine Project To Use Spring MVC Using Java Config, and i set the logging level for spring as INFO to check the initialization log.
This is what am getting upon initialization,
14:52:37,885 INFO [org.springframework.web.servlet.DispatcherServlet] - FrameworkServlet 'SpringMvcConfig': initialization started
14:52:37,885 INFO [org.springframework.web.servlet.DispatcherServlet] - FrameworkServlet 'SpringMvcConfig': initialization started
14:52:37,927 INFO [org.springframework.web.context.support.AnnotationConfigWebApplicationContext] - Refreshing WebApplicationContext for namespace 'SpringMvcConfig-servlet': startup date [Sun Sep 08 14:52:37 UTC 2013]; root of context hierarchy
14:52:37,927 INFO [org.springframework.web.context.support.AnnotationConfigWebApplicationContext] - Refreshing WebApplicationContext for namespace 'SpringMvcConfig-servlet': startup date [Sun Sep 08 14:52:37 UTC 2013]; root of context hierarchy
14:52:38,087 INFO [org.springframework.context.annotation.ClassPathBeanDefinitionScanner] - JSR-330 'javax.inject.Named' annotation found and supported for component scanning
14:52:38,087 INFO [org.springframework.context.annotation.ClassPathBeanDefinitionScanner] - JSR-330 'javax.inject.Named' annotation found and supported for component scanning
14:52:38,093 INFO [org.springframework.web.context.support.AnnotationConfigWebApplicationContext] - Successfully resolved class for [com.test.config.SpringMvcConfig]
14:52:38,093 INFO [org.springframework.web.context.support.AnnotationConfigWebApplicationContext] - Successfully resolved class for [com.test.config.SpringMvcConfig]
14:52:38,239 INFO [org.springframework.context.annotation.ClassPathBeanDefinitionScanner] - JSR-330 'javax.inject.Named' annotation found and supported for component scanning
14:52:38,239 INFO [org.springframework.context.annotation.ClassPathBeanDefinitionScanner] - JSR-330 'javax.inject.Named' annotation found and supported for component scanning
14:52:38,826 INFO [org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor] - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
14:52:38,826 INFO [org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor] - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
14:52:38,987 INFO [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#7fa6e654: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,springMvcConfig,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,mainController,org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration,requestMappingHandlerMapping,mvcContentNegotiationManager,mvcConversionService,viewControllerHandlerMapping,beanNameHandlerMapping,resourceHandlerMapping,defaultServletHandlerMapping,requestMappingHandlerAdapter,mvcValidator,httpRequestHandler Adapter,simpleControllerHandlerAdapter,handlerExceptionResolver,getInternalResourceViewResolver]; root of factory hierarchy
14:52:38,987 INFO [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#7fa6e654: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,springMvcConfig,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,mainController,org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration,requestMappingHandlerMapping,mvcContentNegotiationManager,mvcConversionService,viewControllerHandlerMapping,beanNameHandlerMapping,resourceHandlerMapping,defaultServletHandlerMapping,requestMappingHandlerAdapter,mvcValidator,httpRequestHandlerAdapter,simpleControllerHandlerAdapter,handlerExceptionResolver,getInternalResourceViewResolver]; root of factory hierarchy
14:52:39,378 INFO [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping] - Mapped "{[/ || /login],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto java.lang.String com.test.controller.MainController.hanldeRequest()
14:52:39,378 INFO [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping] - Mapped "{[/ || /login],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto java.lang.String com.test.controller.MainController.hanldeRequest()
14:52:39,449 INFO [org.springframework.web.servlet.handler.SimpleUrlHandlerMapping] - Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler]
14:52:39,449 INFO [org.springframework.web.servlet.handler.SimpleUrlHandlerMapping] - Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler]
14:52:40,355 INFO [org.springframework.web.servlet.DispatcherServlet] - FrameworkServlet 'SpringMvcConfig': initialization completed in 2468 ms
14:52:40,355 INFO [org.springframework.web.servlet.DispatcherServlet] - FrameworkServlet 'SpringMvcConfig': initialization completed in 2468 ms
spring mvc is initialized twice, following is my configuration
web.xml
<servlet>
<servlet-name>SpringMvcConfig</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
com.test.config.SpringMvcConfig
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMvcConfig</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
and My Spring MVC Configuration looks like this,
#Configuration
#EnableWebMvc
#ComponentScan("com.test.controller")
public class SpringMvcConfig extends WebMvcConfigurerAdapter {
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(false).favorParameter(true).ignoreAcceptHeader(true)
.useJaf(false).defaultContentType(MediaType.APPLICATION_JSON).mediaType("json", MediaType.APPLICATION_JSON);
}
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setObjectMapper(new CustomJacksonObjectMapper());
converters.add(converter);
}
#Bean
public InternalResourceViewResolver getInternalResourceViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
resolver.setCache(false);
return resolver;
}
}
Can anyone help me fix this?
Any Solution or suggestion would be very helpful.
Thanks!
If we look at your log4j.properties file
log4j.rootLogger=DEBUG, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d{HH:mm:ss,SSS} %-5p [%c] - %m%n
log4j.logger.org.apache = WARN, A1
log4j.logger.org.springframework = INFO, A1
Both the logger for org.springframework and the root logger are configured to use the A1 appender. If you don't set the additivity flag to false, they will both append.
Appender Additivity
The output of a log statement of logger C will go
to all the appenders in C and its ancestors. This is the meaning of
the term "appender additivity".
However, if an ancestor of logger C, say P, has the additivity flag set to false, then C's output will be directed to all the appenders in C and its ancestors upto and including P but not the appenders in any of the ancestors of P.
Loggers have their additivity flag set to true by default.
log4j.additivity.org.springframework=false
Either do that or remove the A1 appender from the rootLogger
log4j.rootLogger=DEBUG
i had a very similar problem in tomcat because the context was being loaded twice. once by a context load listener (to configure a servlet filter) and once by the dispatch servlet. so i wonder if you are doing something similar?
in other words, some things in spring load contexts by default. try disabling the explicit loading of context and see what happens.
in my case, the solution was to separate the contexts - have different contexts for the filter and servlet. then each was loaded correctly without overlap.
edit: hmm, expanding comments i see you've found a similar answer. i'd encourage you to follow that up more closely. you really need to work out what is loading the extra context. look for context files with "special" names (eg named after a servlet or similar). then try changing their names, for example. in short - you need to find / break the auto-load.
Related
This question already has answers here:
Why is my Spring #Autowired field null?
(21 answers)
Closed 3 years ago.
[RESOLVED] In this case the problem was that I haven't included into the build path some useful libs such as "jersey-spring4-2.28.jar" and "spring-bridge-2.5.0.jar". These libraries allow integration between Jersey and Spring.
I'm working on a web-app on Tomcat (9.0.16), which exposes useful REST services for data communication (services made with the help of Jersey 2.28). In the class that manages these services I used Spring (v5.1.5) to inject the dependencies as follows:
package it.learning.rest;
#Component
#Path("/")
public class GameClientCommsRestService {
#Autowired
#Qualifier("CommunicationBusiness")
private GameClientCommunication comm;
#GET
#Path("/test/check/bean")
#Produces(MediaType.TEXT_PLAIN)
public Response testCheckCommsBean() {
StringBuilder sb = new StringBuilder();
if (comm == null) {
sb.append("GameClientCommunication instance is NULL!!");
} else {
sb.append("GameClientCommunication instance is NOT NULL ---> SUCCESSFULLY instantiated");
}
return getRestResponse(sb.toString());
}
}
The class for which the dependency is injected is defined as follows:
package it.learning.business.impl;
public class GameClientCommunicationBusiness implements GameClientCommunication {
#Override
public String processesMessage(String request, String remoteIpAddress) {
// Processing input...
}
}
The XML configuration file is the following:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="it.learning" />
<context:annotation-config />
<bean id="applicationContextProvider" class="it.learning.utils.spring.ApplicationContextProvider">
</bean>
<bean id="CommunicationBusiness" class="it.learning.business.impl.GameClientCommunicationBusiness">
</bean>
</beans>
On application start-up, neither Tomcat nor the log service records any problems, but if I call
testCheckCommsBean()
it returns
"GameClientCommunication instance is NULL!!"
If instead I use the ApplicationContext object to get the instance associated with "CommunicationBusiness", I get a properly functioning object.
The log shows that both the annotated beans and those declared in the XML file were successfully created and inserted into the Spring container:
2019-03-19 13:06:00,343 DEBUG org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loaded 7 bean definitions from ServletContext resource [/WEB-INF/spring/appContext.xml]
2019-03-19 13:06:00,362 DEBUG org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loaded 4 bean definitions from ServletContext resource [/WEB-INF/spring/appContextBeans.xml]
2019-03-19 13:06:00,438 DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
2019-03-19 13:06:00,526 DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'
2019-03-19 13:06:00,530 DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
2019-03-19 13:06:00,532 DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
2019-03-19 13:06:00,533 DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
2019-03-19 13:06:00,537 DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalPersistenceAnnotationProcessor'
2019-03-19 13:06:00,549 DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'gameClientCommsRestService'
2019-03-19 13:06:00,579 DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'CommunicationBusiness'
2019-03-19 13:06:00,582 DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'applicationContextProvider'
Differently from what reported in
Why is my Spring #Autowired field null?
I never instantiated a "GameClientCommunication" object using the "new" keyword, therefore I really don't understand why the field annotated with #Autowired is null.
Thanks for your support!
You can try #component annotation on top of GameClientCommunicationBusiness class.
The problem is you didn't wire the implementation class.
situation
I have a spring boot application that run a simple REST Service. I want to test this service. Since I love Spock Framework I'd love to use it here but I can't get pass the issue with the Spring Configuration.
problem
The test itself does run but is throwing a java.net.ConnectException: Connection refused: connect exception. The issue here is that the actual application I want to test against is not running - therefore there is not REST interface available. How can I assure that the actual application is running before the test runs? Using JUnit this concern was kinda trivial since Spring has its annotations for that. But what about Spock?
Edit: I tried to use the following article: http://henningpetersen.com/post/18/testing-spring-mvc-controllers-with-spock
RestHandler.java
#RestController
public class RestHandler {
private #Autowired ExecutionService executionService;
public RestHandler(ExecutionService executionService) {
this.executionService = executionService;
}
#RequestMapping(value = "/toolbox/exec", method = POST,
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.TEXT_PLAIN_VALUE)
public String executeTool(#RequestBody Tool tool) {
executionService.execute(tool);
return "thanks";
}
}
ToolExecutor.java
#SpringBootApplication
public class ToolExecutor {
public static void main(String[] args) {
SpringApplication.run(ToolExecutor.class, args);
}
}
RestHandlerTest.groovy
#SpringBootTest
class RestHandlerTest extends Specification {
def someService = Mock(ExecutionService)
def underTest = new RestHandler(someService);
def mockMvc = MockMvcBuilders.standaloneSetup(underTest).build()
#Shared
def client = new RESTClient("http://localhost:603/toolbox/exec")
def "ExecuteToolTest"() {
when: "If POST has valid JSON format"
Closure object = { "{\"name\":\"test\",\"parameters\":[\"abc\",\"def\"]}" }
def response = client.request(Method.POST, object);
then:
with(response){
data.text == "thanks"
status == 200
}
}
}
LOG
15:22:07.601 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemProperties] PropertySource with lowest search precedence
15:22:07.605 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemEnvironment] PropertySource with lowest search precedence
15:22:07.605 [main] DEBUG org.springframework.core.env.StandardEnvironment - Initialized StandardEnvironment with PropertySources [systemProperties,systemEnvironment]
15:22:07.855 [main] DEBUG org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping - Looking for request mappings in application context: org.springframework.test.web.servlet.setup.StubWebApplicationContext#17f9d882
15:22:07.897 [main] DEBUG org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping - 2 request handler methods found on class com.company.toolbox.components.executor.RestHandler: {public void com.company.toolbox.components.executor.RestHandler.isAlive()={[/toolbox/exec],methods=[GET]}, public java.lang.String com.company.toolbox.components.executor.RestHandler.executeTool(com.company.toolbox.commons.Tool)={[/toolbox/exec],methods=[POST],consumes=[application/json],produces=[text/plain]}}
15:22:07.900 [main] INFO org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping - Mapped "{[/toolbox/exec],methods=[GET]}" onto public void com.company.toolbox.components.executor.RestHandler.isAlive()
15:22:07.907 [main] INFO org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping - Mapped "{[/toolbox/exec],methods=[POST],consumes=[application/json],produces=[text/plain]}" onto public java.lang.String com.company.toolbox.components.executor.RestHandler.executeTool(com.company.toolbox.commons.Tool)
15:22:08.285 [main] DEBUG org.jboss.logging - Logging Provider: org.jboss.logging.Slf4jLoggerProvider
15:22:08.286 [main] INFO org.hibernate.validator.internal.util.Version - HV000001: Hibernate Validator 5.3.4.Final
15:22:08.307 [main] DEBUG org.hibernate.validator.internal.engine.resolver.DefaultTraversableResolver - Cannot find javax.persistence.Persistence on classpath. Assuming non JPA 2 environment. All properties will per default be traversable.
15:22:08.317 [main] DEBUG org.hibernate.validator.internal.engine.ConfigurationImpl - Setting custom MessageInterpolator of type org.springframework.validation.beanvalidation.LocaleContextMessageInterpolator
15:22:08.318 [main] DEBUG org.hibernate.validator.internal.engine.ConfigurationImpl - Setting custom ParameterNameProvider of type com.sun.proxy.$Proxy26
15:22:08.320 [main] DEBUG org.hibernate.validator.internal.xml.ValidationXmlParser - Trying to load META-INF/validation.xml for XML based Validator configuration.
15:22:08.323 [main] DEBUG org.hibernate.validator.internal.xml.ResourceLoaderHelper - Trying to load META-INF/validation.xml via TCCL
15:22:08.324 [main] DEBUG org.hibernate.validator.internal.xml.ResourceLoaderHelper - Trying to load META-INF/validation.xml via Hibernate Validator's class loader
15:22:08.324 [main] DEBUG org.hibernate.validator.internal.xml.ValidationXmlParser - No META-INF/validation.xml found. Using annotation based configuration only.
15:22:08.386 [main] INFO org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter - Looking for #ControllerAdvice: org.springframework.test.web.servlet.setup.StubWebApplicationContext#17f9d882
15:22:08.422 [main] DEBUG org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver - Looking for exception mappings: org.springframework.test.web.servlet.setup.StubWebApplicationContext#17f9d882
15:22:08.442 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Initializing servlet ''
15:22:08.452 [main] DEBUG org.springframework.web.context.support.StandardServletEnvironment - Adding [servletConfigInitParams] PropertySource with lowest search precedence
15:22:08.452 [main] DEBUG org.springframework.web.context.support.StandardServletEnvironment - Adding [servletContextInitParams] PropertySource with lowest search precedence
15:22:08.455 [main] DEBUG org.springframework.web.context.support.StandardServletEnvironment - Adding [systemProperties] PropertySource with lowest search precedence
15:22:08.455 [main] DEBUG org.springframework.web.context.support.StandardServletEnvironment - Adding [systemEnvironment] PropertySource with lowest search precedence
15:22:08.455 [main] DEBUG org.springframework.web.context.support.StandardServletEnvironment - Initialized StandardServletEnvironment with PropertySources [servletConfigInitParams,servletContextInitParams,systemProperties,systemEnvironment]
15:22:08.455 [main] INFO org.springframework.mock.web.MockServletContext - Initializing Spring FrameworkServlet ''
15:22:08.455 [main] INFO org.springframework.test.web.servlet.TestDispatcherServlet - FrameworkServlet '': initialization started
15:22:08.457 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Unable to locate MultipartResolver with name 'multipartResolver': no multipart request handling provided
15:22:08.458 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Using LocaleResolver [org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver#267f474e]
15:22:08.458 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Using ThemeResolver [org.springframework.web.servlet.theme.FixedThemeResolver#7a7471ce]
15:22:08.458 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Using RequestToViewNameTranslator [org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator#28276e50]
15:22:08.458 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Using FlashMapManager [org.springframework.web.servlet.support.SessionFlashMapManager#62e70ea3]
15:22:08.458 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Published WebApplicationContext of servlet '' as ServletContext attribute with name [org.springframework.web.servlet.FrameworkServlet.CONTEXT.]
15:22:08.458 [main] INFO org.springframework.test.web.servlet.TestDispatcherServlet - FrameworkServlet '': initialization completed in 3 ms
15:22:08.458 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Servlet '' configured successfully
15:22:08.476 [main] DEBUG groovyx.net.http.RESTClient - POST http://localhost:603/toolbox/exec
15:22:08.728 [main] DEBUG org.apache.http.impl.conn.BasicClientConnectionManager - Get connection for route {}->http://localhost:603
15:22:08.742 [main] DEBUG org.apache.http.impl.conn.DefaultClientConnectionOperator - Connecting to localhost:603
15:22:09.744 [main] DEBUG org.apache.http.impl.conn.DefaultClientConnectionOperator - Connect to localhost:603 timed out. Connection will be retried using another IP address
15:22:09.745 [main] DEBUG org.apache.http.impl.conn.DefaultClientConnectionOperator - Connecting to localhost:603
15:22:10.745 [main] DEBUG org.apache.http.impl.conn.DefaultClientConnection - Connection org.apache.http.impl.conn.DefaultClientConnection#21362712 closed
15:22:10.745 [main] DEBUG org.apache.http.impl.conn.DefaultClientConnection - Connection org.apache.http.impl.conn.DefaultClientConnection#21362712 shut down
15:22:10.746 [main] DEBUG org.apache.http.impl.conn.BasicClientConnectionManager - Releasing connection org.apache.http.impl.conn.ManagedClientConnectionImpl#27eb3298
EXCEPTION
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:120)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:179)
at org.apache.http.impl.conn.ManagedClientConnectionImpl.open(ManagedClientConnectionImpl.java:328)
at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:612)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:447)
at org.apache.http.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:884)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:55)
at groovyx.net.http.HTTPBuilder.doRequest(HTTPBuilder.java:476)
at groovyx.net.http.HTTPBuilder.doRequest(HTTPBuilder.java:441)
at groovyx.net.http.HTTPBuilder.request(HTTPBuilder.java:373)
at com.xetra11.toolbox.components.executor.RestHandlerTest.ExecuteToolTest(RestHandlerTest.groovy:26)
Process finished with exit code -1
This is what you need
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class RestHandlerTest extends Specification {
#Autowired
TestRestTemplate testRestTemplate
And then you use testRestTemplate instead of client. You also need to add spock-spring dependency.
I'm learning about using AOP about RESTful webservices. I choose Tomcat as platform and Weld to bring CDI, I also use CXF as JAX-RS implementation (this is a commitee specific technological constraint in which I am pretty new). This is my sandbox.
As far as I can see Weld is correctly loaded, I got Tomcat + Weld configuration from here, and it find my interceptor (here is a log snapshot):
...
2017-02-02 11:26:03 DEBUG Bootstrap:238 - WELD-000105: Enabled interceptor types for Weld BeanManager for /SecProof_/WEB-INF/classes [bean count=2]:
- class org.jboss.weld.context.activator.ActivateRequestContextInterceptor,
- class edu.pezzati.sec.CanAccessImpl
2017-02-02 11:26:03 DEBUG Bootstrap:236 - WELD-000103: Enabled alternatives for Weld BeanManager for org.jboss.weld.environment.deployment.WeldDeployment.additionalClasses [bean count=3]: (empty collection)
2017-02-02 11:26:03 DEBUG Bootstrap:237 - WELD-000104: Enabled decorator types for Weld BeanManager for org.jboss.weld.environment.deployment.WeldDeployment.additionalClasses [bean count=3]: (empty collection)
2017-02-02 11:26:03 DEBUG Bootstrap:238 - WELD-000105: Enabled interceptor types for Weld BeanManager for org.jboss.weld.environment.deployment.WeldDeployment.additionalClasses [bean count=3]:
- class org.jboss.weld.context.activator.ActivateRequestContextInterceptor
2017-02-02 11:26:03 INFO servletTomcat:45 - WELD-ENV-001100: Tomcat 7+ detected, CDI injection will be available in Servlets, Filters and Listeners.
2017-02-02 11:26:03 TRACE Bean:300 - WELD-001536: Found [] constructors annotated with #Inject for [EnhancedAnnotatedTypeImpl] public #Path class edu.pezzati.sec.WebBoundary
2017-02-02 11:26:03 TRACE Bean:300 - WELD-001536: Found [] constructors annotated with #Inject for [EnhancedAnnotatedTypeImpl] public #CanAccess #Interceptor class edu.pezzati.sec.CanAccessImpl
2017-02-02 11:26:03 TRACE Bean:309 - WELD-000002: Exactly one constructor ([EnhancedAnnotatedConstructorImpl] public edu.pezzati.sec.WebBoundary()) defined, using it as the bean constructor for [EnhancedAnnotatedTypeImpl] public #Path class edu.pezzati.sec.WebBoundary
2017-02-02 11:26:03 TRACE Bean:309 - WELD-000002: Exactly one constructor ([EnhancedAnnotatedConstructorImpl] public edu.pezzati.sec.CanAccessImpl()) defined, using it as the bean constructor for [EnhancedAnnotatedTypeImpl] public #CanAccess #Interceptor class edu.pezzati.sec.CanAccessImpl
2017-02-02 11:26:03 TRACE Bean:300 - WELD-001536: Found [] constructors annotated with #Inject for [EnhancedAnnotatedTypeImpl] public #CanAccess #Interceptor class edu.pezzati.sec.CanAccessImpl
2017-02-02 11:26:03 TRACE Bean:309 - WELD-000002: Exactly one constructor ([EnhancedAnnotatedConstructorImpl] public edu.pezzati.sec.CanAccessImpl()) defined, using it as the bean constructor for [EnhancedAnnotatedTypeImpl] public #CanAccess #Interceptor class edu.pezzati.sec.CanAccessImpl
2017-02-02 11:26:03 TRACE Bean:300 - WELD-001536: Found [] constructors annotated with #Inject for [EnhancedAnnotatedTypeImpl] public #Path class edu.pezzati.sec.WebBoundary
...
Well, I can reach my trivial service but my interceptor is not triggered. Here is what Tomcat gives back to me:
...
INFORMAZIONI: Server startup in 2293 ms
2017-02-02 11:28:59 TRACE Servlet:232 - WELD-000708: Initializing request org.apache.catalina.connector.Request#2b2c4052
2017-02-02 11:28:59 DEBUG Reflection:82 - WELD-000620: interface javax.enterprise.inject.Intercepted is not declared #Target(METHOD, FIELD, PARAMETER, TYPE). Weld will use this annotation, however this may make the application unportable.
2017-02-02 11:28:59 DEBUG Reflection:82 - WELD-000620: interface javax.enterprise.inject.Decorated is not declared #Target(METHOD, FIELD, PARAMETER, TYPE). Weld will use this annotation, however this may make the application unportable.
2017-02-02 11:28:59 TRACE Context:69 - WELD-000222: Loading bean store org.jboss.weld.context.beanstore.http.LazySessionBeanStore#366ca776 map from session null
2017-02-02 11:28:59 TRACE DefaultListableBeanFactory:568 - No bean named 'org.apache.cxf.phase.PhaseManager' found in org.springframework.beans.factory.support.DefaultListableBeanFactory#2c80a98d: defining beans [cxf,org.apache.cxf.bus.spring.BusWiringBeanFactoryPostProcessor,org.apache.cxf.bus.spring.Jsr250BeanPostProcessor,org.apache.cxf.bus.spring.BusExtensionPostProcessor,sec,secproof]; root of factory hierarchy
2017-02-02 11:28:59 TRACE DefaultListableBeanFactory:568 - No bean named 'org.apache.cxf.policy.PolicyDataEngine' found in org.springframework.beans.factory.support.DefaultListableBeanFactory#2c80a98d: defining beans [cxf,org.apache.cxf.bus.spring.BusWiringBeanFactoryPostProcessor,org.apache.cxf.bus.spring.Jsr250BeanPostProcessor,org.apache.cxf.bus.spring.BusExtensionPostProcessor,sec,secproof]; root of factory hierarchy
2017-02-02 11:28:59 TRACE Servlet:293 - WELD-000709: Destroying request org.apache.catalina.connector.Request#2b2c4052
...
What am I missing?
Nevermind. It was only lack of configuration. I had to use the cxf-integration-cdi to make it works this blog post and this example were fundamentals. Thanks goes to the author.
I use spring-boot-starter-parent as parent and add spring-boot-starter-web as denpendency.
By add the #SpringBootApplication annotation, it works.
But DispatcherServlet need initialization
Initializing servlet 'dispatcherServlet'
FrameworkServlet 'dispatcherServlet': initialization started
Using MultipartResolver [org.springframework.web.multipart.support.StandardServletMultipartResolver#745f40ac]
Unable to locate LocaleResolver with name 'localeResolver': using default [org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver#219fc57d]
Unable to locate ThemeResolver with name 'themeResolver': using default [org.springframework.web.servlet.theme.FixedThemeResolver#7b4bd6bd]
Unable to locate RequestToViewNameTranslator with name 'viewNameTranslator': using default [org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator#71ccfa36]
Unable to locate FlashMapManager with name 'flashMapManager': using default [org.springframework.web.servlet.support.SessionFlashMapManager#43f3e6a9]
Published WebApplicationContext of servlet 'dispatcherServlet' as ServletContext attribute with name [org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcherServlet]
FrameworkServlet 'dispatcherServlet': initialization completed in 37 ms
I hope I can set it's loadonstartup by 1, and don't want to use this
annoying BeanNameUrlHandlerMapping, it rejected everything and I'm not going to use it.
o.s.w.s.h.BeanNameUrlHandlerMapping : Rejected bean name 'contextAttributes': no URL paths identified
I read the java-doc about BeanNameUrlHandlerMapping:
This is the default implementation used by the org.springframework.web.servlet.DispatcherServlet, along with org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping (on Java 5 and higher). Alternatively, SimpleUrlHandlerMapping allows for customizing a handler mapping declaratively.
That's all, I just want to change these two thing:
setLoadonStartup
don't use BeanNameUrlHandlerMapping
Beside that, other thing spring boot configure for me is very great, and I want to keep it.
Thank you for any help you can provide.
New reply to old post. Seems this is easier to do with more recent versions of Spring Boot. Just adding the property spring.mvc.servlet.load-on-startup=1 works for me.
I encountered the same problem with loadOnStartup. I solved it by using a custom BeanFactoryPostProcessor to modify the BeanDefinition of the ServletRegistrationBean that Spring Boot creates for registering the DispatcherServlet.
The following code will set loadOnStartup for the DispatcherServlet in a Spring Boot app, when used within an #Configuration class:
#Bean
public static BeanFactoryPostProcessor beanFactoryPostProcessor() {
return new BeanFactoryPostProcessor() {
#Override
public void postProcessBeanFactory(
ConfigurableListableBeanFactory beanFactory) throws BeansException {
BeanDefinition bean = beanFactory.getBeanDefinition(
DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME);
bean.getPropertyValues().add("loadOnStartup", 1);
}
};
}
BTW, the BeanNameUrlHandlerMapping is harmless here.
It is used to map a Spring Bean to a URL - for example it might be used to support Spring HttpInvoker remoting.
The rejection lines in the log output simply mean that it doesn't recognize any of the Spring beans as beans that require a URL mapping. Annoying messages but harmless. You could always set the logging level for this bean or its package to INFO or above to remove the message. In Spring Boot's application.properties put
logging.level.org.springframework.web.servlet.handler=INFO
We are using Spring 3.1.2 and have a String bean defined for our client-side stuff:
<bean name="clientVersion" class="java.lang.String">
<constructor-arg value="CLIENT_VERSION" />
</bean>
This gets used for various things within our beans. I want to be able to use it in the <resources> tag to map some of our static resources. I tried this:
<resources mapping="/#{clientVersion}/**" location="/path/to/versioned/resources/#{clientVersion}/" />
It seems to work for the mapping attribute. I see this on server startup:
INFO o.s.w.s.h.SimpleUrlHandlerMapping - Mapped URL path [/CLIENT_VERSION/**] onto handler 'org.springframework.web.servlet.resource.ResourceHttpRequestHandler#2'
However, when I actually hit a URL under CLIENT_VERSION(e.g. "CLIENT_VERSION/all.js"), I see this in the logs:
DEBUG o.s.w.s.h.SimpleUrlHandlerMapping - URI Template variables for request [/CLIENT_VERSION/all.js] are {}
DEBUG o.s.w.s.h.SimpleUrlHandlerMapping - Mapping [/CLIENT_VERSION/all.js] to HandlerExecutionChain with handler [org.springframework.web.servlet.resource.ResourceHttpRequestHandler#7dad45af] and 1 interceptor
DEBUG o.s.w.s.DispatcherServlet - Last-Modified value for [/CLIENT_VERSION/all.js] is: -1
DEBUG o.s.w.s.r.ResourceHttpRequestHandler - Trying relative path [all.js] against base location: ServletContext resource [/path/to/versioned/resources/#{clientVersion}/]
DEBUG o.s.w.s.r.ResourceHttpRequestHandler - No matching resource found - returning 404
My guess is that it's trying to find the file at /path/to/versioned/resources/#{clientVersion}/all.js, and since the file is at the path /path/to/versioned/resources/CLIENT_VERSION/all.js, it doesn't find it.
Is there a way for the location attribute to resolve #{clientVersion} like the mapping attribute does? Is there another way to accomplish this?