Spring Boot Filter error, Failed to register after unregistered Filter - spring

Im both new to Spring Boot and Kotlin.
I'm having an error saying that
Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalArgumentException:
Cannot register after unregistered Filter class com.jxinternet.platform.ms.merchant.config.security.ReplaceResponseFilter
2018-10-03 15:50:21.601 ERROR 63436 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalArgumentException: Cannot register after unregistered Filter class com.jxinternet.platform.ms.merchant.config.security.ReplaceResponseFilter
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:587)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1250)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1099)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:541)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:501)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:760)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:395)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:327)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1255)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1243)
at com.jxinternet.platform.ms.merchant.MerchantApplicationKt.main(MerchantApplication.kt:28)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalArgumentException: Cannot register after unregistered Filter class com.jxinternet.platform.ms.merchant.config.security.ReplaceResponseFilter
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:579)
... 20 common frames omitted
Caused by: java.lang.IllegalArgumentException: Cannot register after unregistered Filter class com.jxinternet.platform.ms.merchant.config.security.ReplaceResponseFilter
at org.springframework.security.config.annotation.web.builders.FilterComparator.registerAfter(FilterComparator.java:156)
at org.springframework.security.config.annotation.web.builders.HttpSecurity.addFilterAfter(HttpSecurity.java:1121)
at com.jxinternet.platform.ms.merchant.config.security.WebSecurityConfig.configure(WebSecurityConfig.kt:64)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.getHttp(WebSecurityConfigurerAdapter.java:230)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:321)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:92)
at com.jxinternet.platform.ms.merchant.config.security.WebSecurityConfig$$EnhancerBySpringCGLIB$$7e2d609b.init(<generated>)
at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.init(AbstractConfiguredSecurityBuilder.java:371)
at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.doBuild(AbstractConfiguredSecurityBuilder.java:325)
at org.springframework.security.config.annotation.AbstractSecurityBuilder.build(AbstractSecurityBuilder.java:41)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain(WebSecurityConfiguration.java:104)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$f5effa1c.CGLIB$springSecurityFilterChain$3(<generated>)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$f5effa1c$$FastClassBySpringCGLIB$$d83091e8.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:361)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$f5effa1c.springSecurityFilterChain(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
... 21 common frames omitted
Disconnected from the target VM, address: '127.0.0.1:51914', transport: 'socket'
Process finished with exit code 1
my ReplaceResponseFilter.kt
package com.jxinternet.platform.ms.merchant.config.security
import org.slf4j.LoggerFactory
import org.springframework.context.annotation.Configuration
import org.springframework.core.annotation.Order
import org.springframework.hateoas.VndErrors
import org.springframework.http.HttpStatus
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.web.filter.GenericFilterBean
import javax.servlet.*
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import javax.servlet.http.HttpServletResponseWrapper
open class ReplaceResponseFilter : Filter {
companion object {
private val log = LoggerFactory.getLogger(ReplaceResponseFilter::class.java)
}
override fun doFilter(request: ServletRequest, response: ServletResponse, filterChain: FilterChain) {
val t = response as HttpServletResponseWrapper
}
override fun init(p0: FilterConfig?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun destroy(){
}
}
my WebSecurityConfig.kt
package com.jxinternet.platform.ms.merchant.config.security
import com.fasterxml.jackson.databind.ObjectMapper
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.builders.WebSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.config.http.SessionCreationPolicy
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
import org.springframework.security.web.firewall.HttpFirewall
import org.springframework.security.web.firewall.StrictHttpFirewall
#Configuration
#EnableWebSecurity
class WebSecurityConfig(
private val tokenAuthenticationService: TokenAuthenticationService,
private val objectMapper: ObjectMapper
) : WebSecurityConfigurerAdapter() {
// 防止防止url带两个// spring security 5会有问题 所以必须放开这个配置
#Bean
fun allowUrlEncodedSlashHttpFirewall(): HttpFirewall {
val firewall = StrictHttpFirewall()
firewall.setAllowUrlEncodedSlash(true)
return firewall
}
override fun configure(web: WebSecurity) {
super.configure(web)
web.httpFirewall(allowUrlEncodedSlashHttpFirewall())
}
// 设置 HTTP 验证规则
override fun configure(http: HttpSecurity) {
// 关闭csrf验证
http.csrf().disable()
// 对请求进行认证
.authorizeRequests()
// 所有 / 的所有请求 都放行
.antMatchers(
"/",
"/pay/**",
"/scan/**",
"/login",
"/actuator/health",
"/webjars/springfox-swagger-ui/**",
"/swagger-ui.html",
"/configuration/ui",
"/swagger-resources",
"/v2/api-docs",
"/swagger-resources/**").permitAll()
// 所有 /login 的POST请求 都放行
// 所有请求需要身份认证
.anyRequest().authenticated()
.and()
// 添加一个过滤器 所有访问 /login 的请求交给 JWTLoginFilter 来处理 这个类处理所有的JWT相关内容
//.addFilterBefore(loginFilter(objectMapper, tokenAuthenticationService), UsernamePasswordAuthenticationFilter::class.java)
// 添加一个过滤器验证其他请求的Token是否合法
.addFilterBefore(JWTAuthenticationFilter(tokenAuthenticationService, objectMapper), UsernamePasswordAuthenticationFilter::class.java)
.addFilterAfter(ReplaceResponseFilter(), ReplaceResponseFilter::class.java)
// 设置session无状态!!
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
}
}

In ReplaceResponseFilter, you're missing:
filterChain.doFilter(request, response)
Otherwise, your filter chain cannot continue.
I also believe that this is incorrect:
.addFilterAfter(ReplaceResponseFilter(), ReplaceResponseFilter::class.java)
As far as I understand your code, that filter should come after JWTAuthenticationFilter. Therefore:
.addFilterAfter(ReplaceResponseFilter(), JWTAuthenticationFilter::class.java)

Related

Caused by: java.lang.IllegalStateException: Found WebSecurityConfigurerAdapter as well as SecurityFilterChain. Please select just one

I am upgrading spring boot 2.5.12 to Spring boot 2.7.2 in gradle kotlin. As per the link given <https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter > . When I have removed deprecated websecurityconfigureradapter getting exception. Code snippet is given below
#Configuration
#EnableWebSecurity
#Order(1)
public class BasicAuthC {
#Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.requestMatchers().antMatchers("/api/anything"")
.and()
.authorizeRequests(requests -> requests.anyRequest().fullyAuthenticated())
.httpBasic()
return http.build();
}
#Bean
public InMemoryUserDetailsManager memoryUserDetailsManager() {
PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
return new InMemoryUserDetailsManager (User.withUsername("testUserName").password(encoder.encode("****")).
authorities(new SimpleGrantedAuthority("SOME_ROLE")).build());
}
}
import com.azure.spring.aad.webapi.AADJwtBearerTokenAuthenticationConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.web.SecurityFilterChain;
#Order(2)
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
#Configuration
public class OAuthTwoConfiguration {
#Profile(value="OAUTHPROFILE")
#Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/api/test").permitAll()
.and().authorizeRequests((requests) -> requests.anyRequest().authenticated())
.oauth2ResourceServer()
.jwt()
.jwtAuthenticationConverter(new AADJwtBearerTokenAuthenticationConverter());
return http.build();
}
#Profile(value = "test")
#Bean
public WebSecurityCustomizer WebSecurityCustomizer () throws Exception {
return (web)->web.ignoring().antMatchers("/someAPI");
}
}
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalStateException: Found WebSecurityConfigurerAdapter as well as SecurityFilterChain. Please select just one.
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.3.22.jar:5.3.22]
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:653) ~[spring-beans-5.3.22.jar:5.3.22]
... 21 common frames omitted
Caused by: java.lang.IllegalStateException: Found WebSecurityConfigurerAdapter as well as SecurityFilterChain. Please select just one.
at org.springframework.util.Assert.state(Assert.java:76) ~[spring-core-5.3.22.jar:5.3.22]
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain(WebSecurityConfiguration.java:106) ~[spring-security-config-5.7.2.jar:5.7.2]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.3.22.jar:5.3.22]
... 22 common frames omitted
Either your code or some of the libraries that you use are still providing WebSecurityConfigurerAdapter.
Check your code again, maybe you are forgetting some place.
Try to update the libraries that you use to the latest versions.
If they are not migrated yet, you'll might have to wait until they are, before you get rid of WebSecurityConfigurerAdapter.

java.lang.IllegalStateException: Failed to load ApplicationContext ,springboot setting

The following is the error message
java.lang.IllegalStateException: Failed to load ApplicationContext
at
org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)
at
org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108)
at
org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190)
at
org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132)
at
org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246)
at
org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227) at
org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
at
org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at
org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
at
org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
at
org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at
org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at
org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at
org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at
org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at
org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at
org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at
org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at
com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at
com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at
com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at
com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'wokerLogController': Unsatisfied
dependency expressed through field 'client'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'client' defined in class path resource
[com/aurora/backend/config/ESConfig.class]: Bean instantiation via
factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [org.elasticsearch.client.Client]: Factory method 'client'
threw exception; nested exception is java.lang.IllegalStateException:
availableProcessors is already set to [4], rejecting [4] at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
at
org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1378)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:575)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498)
at
org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:846)
at
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:863)
at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546)
at
org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775)
at
org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:316)
at
org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:127)
at
org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
at
org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117)
... 24 more
Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'client' defined in class path resource
[com/aurora/backend/config/ESConfig.class]: Bean instantiation via
factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [org.elasticsearch.client.Client]: Factory method 'client'
threw exception; nested exception is java.lang.IllegalStateException:
availableProcessors is already set to [4], rejecting [4] at
org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:627)
at
org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:456)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1288)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1127)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498)
at
org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at
org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1244)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1164)
at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593)
... 42 more
Caused by: org.springframework.beans.BeanInstantiationException:
Failed to instantiate [org.elasticsearch.client.Client]: Factory
method 'client' threw exception; nested exception is
java.lang.IllegalStateException: availableProcessors is already set to
[4], rejecting [4] at
org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
at
org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:622)
... 55 more Caused by: java.lang.IllegalStateException:
availableProcessors is already set to [4], rejecting [4] at
io.netty.util.NettyRuntime$AvailableProcessorsHolder.setAvailableProcessors(NettyRuntime.java:51)
at
io.netty.util.NettyRuntime.setAvailableProcessors(NettyRuntime.java:87)
at
org.elasticsearch.transport.netty4.Netty4Utils.setAvailableProcessors(Netty4Utils.java:83)
at
org.elasticsearch.transport.netty4.Netty4Transport.(Netty4Transport.java:112)
at
org.elasticsearch.transport.Netty4Plugin.lambda$getTransports$0(Netty4Plugin.java:86)
at
org.elasticsearch.client.transport.TransportClient.buildTemplate(TransportClient.java:189)
at
org.elasticsearch.client.transport.TransportClient.(TransportClient.java:283)
at
org.elasticsearch.transport.client.PreBuiltTransportClient.(PreBuiltTransportClient.java:128)
at
org.elasticsearch.transport.client.PreBuiltTransportClient.(PreBuiltTransportClient.java:114)
at
org.elasticsearch.transport.client.PreBuiltTransportClient.(PreBuiltTransportClient.java:104)
at com.aurora.backend.config.ESConfig.client(ESConfig.java:45) at
com.aurora.backend.config.ESConfig$$EnhancerBySpringCGLIB$$d0b29c5a.CGLIB$client$0()
at
com.aurora.backend.config.ESConfig$$EnhancerBySpringCGLIB$$d0b29c5a$$FastClassBySpringCGLIB$$93c49e6a.invoke()
at
org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244)
at
org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363)
at
com.aurora.backend.config.ESConfig$$EnhancerBySpringCGLIB$$d0b29c5a.client()
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498) at
org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
... 56 more
A springboot project that uses elasticSearch, mysql, redis, etc.
Google has a lot, but he is just a new spingboot. The online stuff doesn't work. I don't know how to change it.
application-local.yml
server:
port: 8000
servlet:
context-path: /api/v3
error:
whitelabel:
enabled: false
spring:
http:
multipart:
encoding:
charset: UTF-8
force: true
enabled: true
datasource:
url: jdbc:mysql://localhost:3306/aurora?useUnicode=yes&characterEncoding=UTF-8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
username: root
password: 123456789
driverClassName: com.mysql.jdbc.Driver
jpa:
database-platform: org.hibernate.dialect.MySQL57Dialect
generate-ddl: true
show-sql: true
liquibase:
change-log: classpath:db/db.master.xml
data:
elasticsearch:
cluster-name: elasticsearch
cluster-nodes: 127.0.0.1:9300
repositories:
enabled: true
redis:
host: 127.0.0.1
port: 6379
password:
database: 0
lettuce:
pool:
max-active: 8
max-wait: -1
max-idle: 8
min-idle: 0
timeout: 0
servlet:
multipart:
max-file-size: 200MB # Max file size.
max-request-size: 215MB # Max Request Size
enabled: true
logging:
pattern:
file: "%d{yy-MM-dd HH:mm:ss.SSS} [%thread] %-5level : %X{user} %logger{36}.%M - %msg%n"
console: "%d{yy-MM-dd HH:mm:ss.SSS} [%thread] %-5level : %X{user} %logger{36}.%M - %msg%n"
level:
org.springframework.web: DEBUG
guru.springframework.controllers: DEBUG
org.hibernate: DEBUG
app:
wechat:
notification: true
design:
root-path: /home/cloudeda/Aurora/UploadData
jwt:
base64-secret: NjkwNjU5ZTg0YmYxZmE0ZDJmYmFlNmMwMGNjMjJjZTc4MjFiZjkyNTk3N2IyN2M5OGQyNzg3ZTExN2M1MGYzMzNkNTg2MzMwODgzZTE3YzIwMDdhMTg1Y2M4ZWFmYmFjOGEyYWNiOTU3ZGYzNTY3NDdmMzg3ZWNjNjRmNjdjNzI=
# Token is valid 24 hours
token-validity-in-seconds: 86400
token-validity-in-seconds-for-remember-me: 2592000
id:
data-center: 1
machine: 1
server:
broker: tcp://localhost:5555
flask:
ibis-parser-url: http://localhost:5050/api/v3/server/parse-ibis-model
generate-report-url: http://localhost:5050/api/v3/server/report
security:
user:
name: aurora
password: aurora-monitor-password
elasticsearch:
host: 127.0.0.1
port: 9300
cluster:
name: elasticsearch
Should be related to the configuration of the ES
ESConfig.java
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.net.InetAddress;
import java.net.UnknownHostException;
#Configuration
public class ESConfig {
#Value("${elasticsearch.host:127.0.0.1}")
private String host;
#Value("${elasticsearch.port:9300}")
private int port;
#Value("${elasticsearch.cluster.name:elasticsearch}")
private String clusterName;
public String getHost() {
return this.host;
}
public int getPort() {
return this.port;
}
#Bean
public Client client() {
TransportClient client = null;
Settings settings = Settings.builder()
.put("cluster.name", clusterName)
.put("client.transport.ignore_cluster_name", false)
.build();
try {
client = new PreBuiltTransportClient(settings)
.addTransportAddress(new TransportAddress(InetAddress.getByName(host), port));
} catch (UnknownHostException e) {
e.printStackTrace();
}
return client;
}
}
Controller
import com.aurora.backend.beans.ResultBean;
import com.aurora.backend.beans.WorkerLogBean;
import com.aurora.backend.param.SearchSimulationLogParam;
import com.aurora.backend.security.CurrentUser;
import com.aurora.backend.security.UserPrincipal;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
#RestController
#RequestMapping(value = "/es")
#Slf4j
public class WokerLogController {
#Autowired Client client;
#PostMapping(value = "/simulation/log")
public ResultBean getSimulationLog(
#CurrentUser UserPrincipal user,
#RequestBody SearchSimulationLogParam param
) {
SearchResponse response = client.prepareSearch("logstash-worker")
.setTypes("doc")
.setSearchType(SearchType.QUERY_THEN_FETCH)
.setQuery(QueryBuilders.matchQuery("logtype", 1))
.setQuery(QueryBuilders.matchQuery("token", param.getToken()))
.setPostFilter(
QueryBuilders.rangeQuery("#timestamp")
.from(param.getStartTime()).to(param.getEndTime()))
.get();
SearchHit[] hits = response.getHits().getHits();
List<WorkerLogBean> mapList = new ArrayList<>();
for (int i = 0; i < hits.length; i++) {
WorkerLogBean logBean = new WorkerLogBean();
logBean.setId(hits[i].getId());
logBean.setLog(hits[i].getSourceAsMap().get("log").toString());
logBean.setMessage(hits[i].getSourceAsMap().get("message").toString());
mapList.add(logBean);
}
return new ResultBean(mapList);
}
}
This is where your exception is:
Caused by:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'wokerLogController': Unsatisfied
dependency expressed through field 'client'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'client' defined in class path resource
and
Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'client' defined in class path resource
[com/aurora/backend/config/ESConfig.class]: Bean instantiation via
factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [org.elasticsearch.client.Client]: Factory method 'client'
threw exception; nested exception is java.lang.IllegalStateException:
availableProcessors is already set to [4], rejecting [4] at
and
Caused by: org.springframework.beans.BeanInstantiationException:
Failed to instantiate [org.elasticsearch.client.Client]: Factory
method 'client' threw exception; nested exception is
java.lang.IllegalStateException: availableProcessors is already set to
[4], rejecting [4] at
This problem has been reported in this link. Haven't faced this problem with elastic search. The following might solve your problem but this might be webserver dependent. Check this.
#Component
public class ElasticSearchConfiguration implements InitializingBean {
static {
System.setProperty("es.set.netty.runtime.available.processors", "false");
}
#Override
public void afterPropertiesSet() throws Exception {
System.out.println(System.getProperty("es.set.netty.runtime.available.processors"));
}
}
It could be a dependency issue. Anyway, if you are using spring boot 2.., go with rest client instead of transport client which is deprecated.
Use the following code:
build.gradle:
compile "com.fasterxml.jackson.datatype:jackson-datatype-hppc"
compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310"
compile "com.fasterxml.jackson.datatype:jackson-datatype-hibernate5"
compile "com.fasterxml.jackson.core:jackson-annotations"
compile "com.fasterxml.jackson.core:jackson-databind"
compile "com.fasterxml.jackson.module:jackson-module-afterburner"
runtime group: 'com.fasterxml.jackson.module', name: 'jackson-modules-java8', version: '2.9.8', ext: 'pom'
// https://mvnrepository.com/artifact/com.fasterxml.jackson.module/jackson-module-parameter-names
compile group: 'com.fasterxml.jackson.module', name: 'jackson-module-parameter-names', version: '2.9.8'
compile 'org.elasticsearch:elasticsearch'
compile 'org.elasticsearch.client:transport'
compile 'org.elasticsearch.client:elasticsearch-rest-client'
compile 'org.elasticsearch.client:elasticsearch-rest-high-level-client'
compile 'org.springframework.data:spring-data-elasticsearch'
Versions: Should be Compatible
org.elasticsearch.client:elasticsearch-rest-client -> 6.4.3 (*)
org.elasticsearch.client:elasticsearch-rest-high-level-client -> 6.4.3
org.elasticsearch:elasticsearch -> 6.4.3
org.springframework.data:spring-data-elasticsearch -> 3.1.4.RELEASE
com.fasterxml.jackson.datatype:jackson-datatype-hppc -> 2.9.8
com.fasterxml.jackson.core:jackson-core:2.9.8
com.fasterxml.jackson.core:jackson-databind:2.9.8 (*)
com.fasterxml.jackson.datatype:jackson-datatype-jsr310 -> 2.9.8 (*)
com.fasterxml.jackson.datatype:jackson-datatype-hibernate5 -> 2.9.8
com.fasterxml.jackson.core:jackson-annotations -> 2.9.0
com.fasterxml.jackson.module:jackson-module-afterburner -> 2.9.8
com.fasterxml.jackson.module:jackson-module-parameter-names:2.9.8 (*)
com.fasterxml.jackson.module:jackson-modules-java8:2.9.8
ElasticSearchConfiguration:
RestHighLevelClient client = null;
#Bean
public RestHighLevelClient buildClient() {
return new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http"),
new HttpHost("localhost", 9201, "http")));
}
#Bean
#Primary
public ElasticsearchOperations elasticsearchTemplate() {
return new ElasticsearchTemplate((Client) buildClient(), new CustomEntityMapper(new ObjectMapper()));
}
public class CustomEntityMapper implements EntityMapper {
private ObjectMapper objectMapper;
public CustomEntityMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
//objectMapper.registerModule(new JavaTimeModule());
JavaTimeModule javaTimeModule=new JavaTimeModule();
// Hack time module to allow 'Z' at the end of string (i.e. javascript json's)
javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ISO_DATE_TIME));
javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ISO_DATE));
objectMapper.registerModule(javaTimeModule);
objectMapper.findAndRegisterModules();
}
#Override
public String mapToString(Object object) throws IOException {
return objectMapper.writeValueAsString(object);
}
#Override
public <T> T mapToObject(String source, Class<T> clazz) throws IOException {
return objectMapper.readValue(source, clazz);
}
}

Class loading error on websphere when upgrading to Spring 4.2.3

When I upgrade a multi-war Spring application from Spring 4.1.8 to 4.2.3 I get a strange ClassNotFoundException in a websphere application server (version 8.5.5). The class that is not found by the classloader is on the classpath and was found with previous releases of Spring.
[11.12.15 10:04:27:536 CET] 0000004f FfdcProvider W com.ibm.ws.ffdc.impl.FfdcProvider logIncident FFDC1003I: FFDC Incident emitted on D:\devsbb\websphere\was8_5\IBM\WebSphere\AppServer\profiles\AppSrv01\logs\ffdc\server1_bc0c2481_15.12.11_10.04.27.4771875357035970693584.txt com.ibm.ws.webcontainer.webapp.WebApp.notifyServletContextCreated 1341
[11.12.15 10:04:27:536 CET] 0000004f webapp E com.ibm.ws.webcontainer.webapp.WebApp notifyServletContextCreated SRVE0283E: Exception caught while initializing context: {0}
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'showCaseViewModel' defined in BeanDefinition defined in file [D:\devsbb\websphere\was8_5\IBM\WebSphere\AppServer\profiles\AppSrv01\installedApps\localhostNode01Cell\template-ear-4.0.3-SNAPSHOT.ear\template-web-jsf.war\WEB-INF\classes\ch\sbb\myapp\presentation\ShowCaseViewModel.class]: Initialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Unexpected AOP exception; nested exception is java.lang.RuntimeException: java.lang.ClassNotFoundException: ch.sbb.myapp.presentation.exception.SampleTranslateableFileCopyException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:753)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:838)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at com.ibm.ws.webcontainer.webapp.WebApp.notifyServletContextCreated(WebApp.java:1689)
at com.ibm.ws.webcontainer.webapp.WebAppImpl.initialize(WebAppImpl.java:414)
at com.ibm.ws.webcontainer.webapp.WebGroupImpl.addWebApplication(WebGroupImpl.java:88)
at com.ibm.ws.webcontainer.VirtualHostImpl.addWebApplication(VirtualHostImpl.java:169)
at com.ibm.ws.webcontainer.WSWebContainer.addWebApp(WSWebContainer.java:749)
at com.ibm.ws.webcontainer.WSWebContainer.addWebApplication(WSWebContainer.java:634)
at com.ibm.ws.webcontainer.component.WebContainerImpl.install(WebContainerImpl.java:426)
at com.ibm.ws.webcontainer.component.WebContainerImpl.start(WebContainerImpl.java:718)
at com.ibm.ws.runtime.component.ApplicationMgrImpl.start(ApplicationMgrImpl.java:1177)
at com.ibm.ws.runtime.component.DeployedApplicationImpl.fireDeployedObjectStart(DeployedApplicationImpl.java:1370)
at com.ibm.ws.runtime.component.DeployedModuleImpl.start(DeployedModuleImpl.java:639)
at com.ibm.ws.runtime.component.DeployedApplicationImpl.start(DeployedApplicationImpl.java:968)
at com.ibm.ws.runtime.component.ApplicationMgrImpl.startApplication(ApplicationMgrImpl.java:776)
at com.ibm.ws.runtime.component.ApplicationMgrImpl$5.run(ApplicationMgrImpl.java:2195)
at com.ibm.ws.security.auth.ContextManagerImpl.runAs(ContextManagerImpl.java:5474)
at com.ibm.ws.security.auth.ContextManagerImpl.runAsSystem(ContextManagerImpl.java:5600)
at com.ibm.ws.security.core.SecurityContext.runAsSystem(SecurityContext.java:255)
at com.ibm.ws.runtime.component.ApplicationMgrImpl.start(ApplicationMgrImpl.java:2200)
at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.start(CompositionUnitMgrImpl.java:389)
at com.ibm.ws.runtime.component.CompositionUnitImpl.start(CompositionUnitImpl.java:123)
at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.start(CompositionUnitMgrImpl.java:332)
at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.access$500(CompositionUnitMgrImpl.java:119)
at com.ibm.ws.runtime.component.CompositionUnitMgrImpl$CUInitializer.run(CompositionUnitMgrImpl.java:938)
at com.ibm.wsspi.runtime.component.WsComponentImpl$_AsynchInitializer.run(WsComponentImpl.java:502)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1864)
Caused by: org.springframework.aop.framework.AopConfigException: Unexpected AOP exception; nested exception is java.lang.RuntimeException: java.lang.ClassNotFoundException: ch.sbb.myapp.presentation.exception.SampleTranslateableFileCopyException
at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:218)
at org.springframework.aop.framework.ProxyFactory.getProxy(ProxyFactory.java:109)
at org.springframework.aop.scope.ScopedProxyFactoryBean.setBeanFactory(ScopedProxyFactoryBean.java:111)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeAwareMethods(AbstractAutowireCapableBeanFactory.java:1597)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1565)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
... 36 more
Caused by: java.lang.RuntimeException: java.lang.ClassNotFoundException: ch.sbb.myapp.presentation.exception.SampleTranslateableFileCopyException
at org.springframework.asm.ClassWriter.getCommonSuperClass(ClassWriter.java:1684)
at org.springframework.asm.ClassWriter.getMergedType(ClassWriter.java:1654)
at org.springframework.asm.Frame.merge(Frame.java:1426)
at org.springframework.asm.Frame.merge(Frame.java:1337)
at org.springframework.asm.MethodWriter.visitMaxs(MethodWriter.java:1475)
at org.springframework.cglib.core.CodeEmitter.visitMaxs(CodeEmitter.java:842)
at org.springframework.cglib.transform.impl.UndeclaredThrowableTransformer$1.visitMaxs(UndeclaredThrowableTransformer.java:56)
at org.springframework.cglib.core.CodeEmitter.visitMaxs(CodeEmitter.java:842)
at org.springframework.cglib.core.CodeEmitter.end_method(CodeEmitter.java:138)
at org.springframework.cglib.proxy.MethodInterceptorGenerator.generate(MethodInterceptorGenerator.java:131)
at org.springframework.cglib.proxy.Enhancer.emitMethods(Enhancer.java:1005)
at org.springframework.cglib.proxy.Enhancer.generateClass(Enhancer.java:509)
at org.springframework.cglib.transform.TransformingClassGenerator.generateClass(TransformingClassGenerator.java:33)
at org.springframework.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
at org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:231)
at org.springframework.cglib.proxy.Enhancer.createHelper(Enhancer.java:378)
at org.springframework.cglib.proxy.Enhancer.createClass(Enhancer.java:318)
at org.springframework.aop.framework.ObjenesisCglibAopProxy.createProxyClassAndInstance(ObjenesisCglibAopProxy.java:55)
at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:202)
... 41 more
Here is my class:
package ch.sbb.myapp.presentation;
import java.util.HashSet;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.sbb.esta.core.stereotype.Scope;
import ch.sbb.esta.core.stereotype.web.EstaViewModel;
import ch.sbb.esta.core.type.Email;
import ch.sbb.myapp.exception.TemplateErrorCode;
import ch.sbb.myapp.model.Customer;
import ch.sbb.myapp.model.CustomerStatus;
import ch.sbb.myapp.model.i18n.I18nMessageKey;
import ch.sbb.myapp.presentation.exception.SampleTranslateableFileCopyException;
/**
* ViewModel für den Primefaces Showcase.
*/
#EstaViewModel(scope = Scope.REQUEST)
public class ShowCaseViewModel {
private static final Logger LOGGER = LoggerFactory.getLogger(ShowCaseViewModel.class);
public boolean isMcaIntegrationInClasspath() {
try {
this.getClass().getClassLoader().loadClass("ch.sbb.myapp.presentation.McaDemoViewModel");
return true;
} catch (ClassNotFoundException e) { // NOSONAR: is just a check whether MCA integration is on the classpath
return false;
}
}
public CustomerStatus getCustomerStatusNull() {
return null;
}
public void setCustomerStatusNull(CustomerStatus t) {
}
public CustomerStatus getCustomerStatus() {
return CustomerStatus.VIP;
}
public void throwEstaException() throws SampleTranslateableFileCopyException {
throw new SampleTranslateableFileCopyException(I18nMessageKey.ERROR_WHILE_CALLING_SERVICE,
TemplateErrorCode.FILE_COPY_ERROR_CODE, "fileA", "fileB");
}
public void logValidationException() {
Customer wrongCustomer = new Customer("fi", "la", new Email("bla#sbb.ch"));
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<Customer>> violations = validator.validate(wrongCustomer);
Set<ConstraintViolation<?>> violationsWithoutType = new HashSet<>();
violationsWithoutType.addAll(violations);
LOGGER.warn("violated exception", new ConstraintViolationException("bla", violationsWithoutType));
}
}
The annotation #EstaViewModel is declared as a simple #Component:
#Inherited
#Component
#Retention(RetentionPolicy.RUNTIME)
#Target({ ElementType.TYPE })
public #interface EstaViewModel {
String value() default "";
Scope scope() default Scope.REQUEST;
}
All other classes with the #EstaViewModel annotation are initialized without any problem.
Any ideas?

Cometd Oort Cluster - Spring Integration

Getting null pointer exception on trying to integrate spring with cometd oort cluster:
<servlet>
<servlet-name>cometd</servlet-name>
<servlet-class>org.cometd.server.CometdServlet</servlet-class>
<init-param>
<param-name>transports</param-name>
<param-value>org.cometd.websocket.server.WebSocketTransport</param-value>
</init-param>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>cometd</servlet-name>
<url-pattern>/cometd/*</url-pattern>
</servlet-mapping>
Found this information on internet
:If you use Spring to configure CometD objects, then you must not use
configuration servlets such as OortMulticastConfigServlet.
All your configuration belongs to Spring and you do everything in the
initializer.
<!--
<servlet>
<servlet-name>oort</servlet-name>
<servlet-class>org.cometd.oort.OortStaticConfigServlet</servlet-class>
<init-param>
<param-name>oort.url</param-name>
<param-value>http://10.30.3.106:9080/project/cometd</param-value>
</init-param>
<init-param>
<param-name>oort.cloud</param-name>
<param-value>http://10.30.1.112:8080/project/cometd</param-value>
</init-param>
</servlet> -->
Does seti need to be configured in web.xml when using Spring ?
<servlet>
<servlet-name>seti</servlet-name>
<servlet-class>org.cometd.oort.SetiServlet</servlet-class>
</servlet>
Cometd Integration with Spring :
package com.efacec.oms.powr.cometd;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.servlet.ServletContext;
import org.apache.log4j.Logger;
import org.cometd.annotation.ServerAnnotationProcessor;
import org.cometd.bayeux.server.BayeuxServer;
import org.cometd.oort.Oort;
import org.cometd.oort.Seti;
import org.cometd.server.BayeuxServerImpl;
import org.cometd.server.ext.TimesyncExtension;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ServletContextAware;
#Component
#Singleton
public class Configurer implements DestructionAwareBeanPostProcessor, ServletContextAware
{
private BayeuxServer bayeuxServer;
private ServerAnnotationProcessor processor;
private Oort oort;
private Seti seti;
private Logger logger = Logger.getLogger(this.getClass());
#Autowired
BayeuxAuthenticator bayeuxAuthenticator;
#Inject
private void setBayeuxServer(BayeuxServer bayeuxServer)
{
this.bayeuxServer = bayeuxServer;
this.bayeuxServer.addExtension(new TimesyncExtension());
// BayeuxAuthenticator authenticator = new BayeuxAuthenticator();
this.bayeuxServer.setSecurityPolicy(bayeuxAuthenticator);
}
#PostConstruct
public void init()
{
this.processor = new ServerAnnotationProcessor(bayeuxServer);
}
public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException
{
processor.processDependencies(bean);
processor.processConfigurations(bean);
processor.processCallbacks(bean);
return bean;
}
public Object postProcessAfterInitialization(Object bean, String name) throws BeansException
{
return bean;
}
public void postProcessBeforeDestruction(Object bean, String name) throws BeansException
{
processor.deprocessCallbacks(bean);
}
#Bean(initMethod = "start", destroyMethod = "stop")
public BayeuxServer bayeuxServer()
{
BayeuxServerImpl bean = new BayeuxServerImpl();
bean.setOption(BayeuxServerImpl.LOG_LEVEL, "3");
// bean.setOption(BayeuxServerImpl., "3");
return bean;
}
#Bean(name="oort", initMethod = "start", destroyMethod="stop")
public Oort oort()
{
oort = new Oort(this.bayeuxServer,"oortion");
//Using bayeuxServer(), throw null pointer exception
return oort;
}
Is it really required to set Attribute Seti and oort on servlet Context?
#Bean(name="seti", initMethod = "start", destroyMethod="stop")
public Seti seti(){
Seti seti = new Seti(oort);
return seti;
}
public void setServletContext(ServletContext servletContext)
{
servletContext.setAttribute(BayeuxServer.ATTRIBUTE, bayeuxServer);
// servletContext.setAttribute(Seti.SETI_ATTRIBUTE, seti);
// servletContext.setAttribute(Oort.OORT_ATTRIBUTE, oort);
}
}
Cannot associate userId with session.
seti.associate(loginUserId, serverSession);
Cannot Inject Seti and OOrt in Security policy.
package com.efacec.oms.powr.cometd;
import java.util.HashMap;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.servlet.ServletContext;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.cometd.bayeux.server.BayeuxServer;
import org.cometd.bayeux.server.ServerMessage;
import org.cometd.bayeux.server.ServerSession;
import org.cometd.oort.Oort;
import org.cometd.oort.OortComet;
import org.cometd.oort.Seti;
import org.cometd.server.DefaultSecurityPolicy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ServletContextAware;
#Component
#Singleton
public class BayeuxAuthenticator extends DefaultSecurityPolicy implements ServerSession.RemoveListener // (1)
{
private Seti seti;
private Oort oort;
private Logger logger = Logger.getLogger(this.getClass());
#Autowired
public void setSeti(Seti seti) {
this.seti = seti;
}
#Autowired
public void setOort(Oort oort) {
this.oort = oort;
}
#Override
public boolean canHandshake(BayeuxServer server, ServerSession serverSession, ServerMessage message) //(2)
{
if (serverSession.isLocalSession()) //(3)
return true;
// Remote Oort comets are allowed to handshake
/* if (oort.isOortHandshake(message))
return true;
*/
Map<String, Object> ext = message.getExt();
if (ext == null)
return false;
#SuppressWarnings("unchecked")
Map<String, Object> authentication = (Map<String, Object>)ext.get("authentication");
if (authentication == null)
return false;
Object user=authentication.get("user");
String loginUserId=user.toString();
boolean user_is_number=StringUtils.isNumeric(loginUserId) ? true:false;
seti.associate(loginUserId, serverSession);
serverSession.addListener(this); // (6)
return true;
}
else
{
logger.debug("Authentication Failure !! ::"+serverSession.getId());
serverSession.addListener(this); // (6)
return false;
}
}
public void removed(ServerSession remote, boolean expired) // (7)
{
}
}
Error Message :
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'configurer': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.efacec.oms.powr.cometd.BayeuxAuthenticator com.efacec.oms.powr.cometd.Configurer.bayeuxAuthenticator; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'bayeuxAuthenticator': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void com.efacec.oms.powr.cometd.BayeuxAuthenticator.setSeti(org.cometd.oort.Seti); nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'seti' defined in class path resource [com/efacec/oms/powr/cometd/Configurer.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.cometd.oort.Seti com.efacec.oms.powr.cometd.Configurer.seti()] threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
at org.springframework.context.support.PostProcessorRegistrationDelegate.registerBeanPostProcessors(PostProcessorRegistrationDelegate.java:232)
at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:618)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:467)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4992)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5490)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.efacec.oms.powr.cometd.BayeuxAuthenticator com.efacec.oms.powr.cometd.Configurer.bayeuxAuthenticator; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'bayeuxAuthenticator': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void com.efacec.oms.powr.cometd.BayeuxAuthenticator.setSeti(org.cometd.oort.Seti); nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'seti' defined in class path resource [com/efacec/oms/powr/cometd/Configurer.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.cometd.oort.Seti com.efacec.oms.powr.cometd.Configurer.seti()] threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
... 23 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'bayeuxAuthenticator': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void com.efacec.oms.powr.cometd.BayeuxAuthenticator.setSeti(org.cometd.oort.Seti); nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'seti' defined in class path resource [com/efacec/oms/powr/cometd/Configurer.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.cometd.oort.Seti com.efacec.oms.powr.cometd.Configurer.seti()] threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1017)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:960)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
... 25 more
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void com.efacec.oms.powr.cometd.BayeuxAuthenticator.setSeti(org.cometd.oort.Seti); nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'seti' defined in class path resource [com/efacec/oms/powr/cometd/Configurer.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.cometd.oort.Seti com.efacec.oms.powr.cometd.Configurer.seti()] threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
... 36 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'seti' defined in class path resource [com/efacec/oms/powr/cometd/Configurer.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.cometd.oort.Seti com.efacec.oms.powr.cometd.Configurer.seti()] threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:597)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1094)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:989)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1017)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:960)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:553)
... 38 more
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.cometd.oort.Seti com.efacec.oms.powr.cometd.Configurer.seti()] threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:188)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:586)
... 50 more
**Caused by: java.lang.NullPointerException
at org.cometd.oort.Seti.<init>(Seti.java:82)
at com.efacec.oms.powr.cometd.Configurer.seti(Configurer.java:100)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at** org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:166)
... 51 more
I have added an example on how to configure Oort and Seti using Spring annotations.
As for your questions:
The NullPointerException is due to the fact that methods on your Configurer class are called in an order that you don't expect. By the way, Configurer should be annotated with Spring's #Configuration rather than #Component (COMETD-547).
SetiServlet is the configuration Servlet for Seti, so if you configure CometD using Spring, you should configure Seti in Spring, not in web.xml.
Setting Oort and Seti as ServletContext attribute is strongly recommended. It's a simple one liner in the Spring configuration, and allows you for full compatibility with code that uses those attributes.
Follow the example I linked above, and everything should be good.

Adding custom behavior to all repositories without xml configuration

I am trying to add custom behavior to all repositories in my spring application but I don't want to use XML configuration, only spring annotation like #xxxx.
So I looked for that on the Internet and I found this documentation.
The problem with the documentation is that it deals with JPA (not MongoDB) and the step 4 is not specific enough for a spring application without xml annotation.
Documentation step 4 :
declare beans of the custom factory directly
How we do that?
So I didn't give up and I looked deeper on the Internet and I found this.
But this time, it was for Solr (not Mongo).
The interesting part is:
import org.springframework.context.annotation.Configuration;
import org.springframework.data.solr.repository.config.EnableSolrRepositories;
#Configuration
#EnableSolrRepositories(
basePackages = "net.petrikainulainen.spring.datasolr.todo.repository.solr",
repositoryFactoryBeanClass = CustomSolrRepositoryFactoryBean.class
)
public class SolrContext {
//Configuration is omitted.
}
But my application still does not work! You can find all the code in github.
Architecture
src/main/java
fr.exemple.test.Application.java
fr.exemple.test.controller.TestController.java
fr.exemple.test.model.domain.Test.java
fr.exemple.test.model.repository.TestRepository.java
fr.exemple.test.model.repository.global.MyRepository.java
fr.exemple.test.model.repository.global.MyRepositoryFactoryBean.java
fr.exemple.test.model.repository.global.MyRepositoryImpl.java
My Code
Application :
package fr.exemple.test;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import fr.exemple.test.model.repository.global.MyRepositoryFactoryBean;
#Configuration
#ComponentScan
#EnableAutoConfiguration
#EnableMongoRepositories(
basePackages = {"fr.exemple.test.repository.global"},
repositoryFactoryBeanClass = MyRepositoryFactoryBean.class
)
public class Application {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(Application.class);
app.setShowBanner(false);
app.run(args);
}
}
TestController :
package fr.exemple.test.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import fr.exemple.test.model.repository.TestRepository;
#RestController
#RequestMapping("/test")
public class TestController {
#Autowired
private TestRepository repository;
#RequestMapping(method=RequestMethod.GET)
public void sharedCustomMethodTest() {
repository.sharedCustomMethod("Hello World !");
}
}
Test :
package fr.exemple.test.model.domain;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document
public class Test {
#Id
private String id;
private String firstName;
private String lastName;
public Test() {}
public Test(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
#Override
public String toString() {
return String.format(
"Customer[id=%s, firstName='%s', lastName='%s']",
id, firstName, lastName);
}
}
TestRepository :
package fr.exemple.test.model.repository;
import fr.exemple.test.model.domain.Test;
import fr.exemple.test.model.repository.global.MyRepository;
public interface TestRepository extends MyRepository<Test, String> {
}
MyRepository :
package fr.exemple.test.model.repository.global;
import java.io.Serializable;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.repository.NoRepositoryBean;
#NoRepositoryBean
public interface MyRepository<T, ID extends Serializable> extends MongoRepository<T, ID>{
void sharedCustomMethod(ID id);
}
MyRepositoryFactoryBean :
package fr.exemple.test.model.repository.global;
import java.io.Serializable;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.query.MongoEntityInformation;
import org.springframework.data.mongodb.repository.support.MappingMongoEntityInformation;
import org.springframework.data.mongodb.repository.support.MongoRepositoryFactory;
import org.springframework.data.mongodb.repository.support.MongoRepositoryFactoryBean;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;
import org.springframework.data.util.ClassTypeInformation;
import org.springframework.data.util.TypeInformation;
public class MyRepositoryFactoryBean<R extends MongoRepository<T, I>, T, I extends Serializable>
extends MongoRepositoryFactoryBean<R, T, I> {
#Override
protected RepositoryFactorySupport getFactoryInstance(MongoOperations operations) {
return new MyRepositoryFactory<T, I>(operations);
}
private static class MyRepositoryFactory<T, I extends Serializable> extends
MongoRepositoryFactory {
private MongoOperations mongoOperations;
public MyRepositoryFactory(MongoOperations mongoOperations) {
super(mongoOperations);
this.mongoOperations = mongoOperations;
}
protected Object getTargetRepository(RepositoryMetadata metadata) {
TypeInformation<T> information = ClassTypeInformation.from((Class<T>)metadata.getDomainType());
MongoPersistentEntity<T> pe = new BasicMongoPersistentEntity<T>(information);
MongoEntityInformation<T,I> mongometa = new MappingMongoEntityInformation<T, I>(pe);
return new MyRepositoryImpl<T, I>(mongometa, mongoOperations);
}
protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
return MyRepository.class;
}
}
}
MyRepositoryImpl :
package fr.exemple.test.model.repository.global;
import java.io.Serializable;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.repository.query.MongoEntityInformation;
import org.springframework.data.mongodb.repository.support.SimpleMongoRepository;
public class MyRepositoryImpl<T, ID extends Serializable> extends
SimpleMongoRepository<T, ID> implements MyRepository<T, ID> {
private Log log = LogFactory.getLog(MyRepositoryImpl.class);
private MongoOperations mongoOperations;
public MyRepositoryImpl(MongoEntityInformation<T, ID> metadata,
MongoOperations mongoOperations) {
super(metadata, mongoOperations);
this.mongoOperations = mongoOperations;
}
#Override
public void sharedCustomMethod(ID id) {
log.info(id);
}
}
Stack Trace
Error starting ApplicationContext. To display the auto-configuration report enabled debug logging (start with --debug)
2014-07-13 11:12:51.951 ERROR 2144 --- [ main] o.s.boot.SpringApplication : Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private fr.exemple.test.model.repository.TestRepository fr.exemple.test.controller.TestController.repository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property shared found for type void!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:120)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at fr.exemple.test.Application.main(Application.java:23)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private fr.exemple.test.model.repository.TestRepository fr.exemple.test.controller.TestController.repository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property shared found for type void!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
... 14 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property shared found for type void!
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1017)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:960)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
... 16 common frames omitted
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property shared found for type void!
at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:75)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:327)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:359)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:359)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:307)
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:270)
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:241)
at org.springframework.data.repository.query.parser.Part.<init>(Part.java:76)
at org.springframework.data.repository.query.parser.PartTree$OrPart.<init>(PartTree.java:213)
at org.springframework.data.repository.query.parser.PartTree$Predicate.buildTree(PartTree.java:321)
at org.springframework.data.repository.query.parser.PartTree$Predicate.<init>(PartTree.java:301)
at org.springframework.data.repository.query.parser.PartTree.<init>(PartTree.java:82)
at org.springframework.data.mongodb.repository.query.PartTreeMongoQuery.<init>(PartTreeMongoQuery.java:52)
at org.springframework.data.mongodb.repository.support.MongoRepositoryFactory$MongoQueryLookupStrategy.resolveQuery(MongoRepositoryFactory.java:128)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:320)
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:169)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:224)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:210)
at org.springframework.data.mongodb.repository.support.MongoRepositoryFactoryBean.afterPropertiesSet(MongoRepositoryFactoryBean.java:108)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1612)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1549)
... 26 common frames omitted
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private fr.exemple.test.model.repository.TestRepository fr.exemple.test.controller.TestController.repository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property shared found for type void!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:120)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at fr.exemple.test.Application.main(Application.java:23)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private fr.exemple.test.model.repository.TestRepository fr.exemple.test.controller.TestController.repository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property shared found for type void!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
... 14 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property shared found for type void!
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1017)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:960)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
... 16 more
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property shared found for type void!
at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:75)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:327)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:359)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:359)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:307)
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:270)
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:241)
at org.springframework.data.repository.query.parser.Part.<init>(Part.java:76)
at org.springframework.data.repository.query.parser.PartTree$OrPart.<init>(PartTree.java:213)
at org.springframework.data.repository.query.parser.PartTree$Predicate.buildTree(PartTree.java:321)
at org.springframework.data.repository.query.parser.PartTree$Predicate.<init>(PartTree.java:301)
at org.springframework.data.repository.query.parser.PartTree.<init>(PartTree.java:82)
at org.springframework.data.mongodb.repository.query.PartTreeMongoQuery.<init>(PartTreeMongoQuery.java:52)
at org.springframework.data.mongodb.repository.support.MongoRepositoryFactory$MongoQueryLookupStrategy.resolveQuery(MongoRepositoryFactory.java:128)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:320)
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:169)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:224)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:210)
at org.springframework.data.mongodb.repository.support.MongoRepositoryFactoryBean.afterPropertiesSet(MongoRepositoryFactoryBean.java:108)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1612)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1549)
... 26 more
This happens as the package structure is not consistent. The base package of #EnableMongoRepositories points to fr.exemple.test.repository.global whereas the repository definition is located in fr.exemple.test.model.repository. As the scan for repositories returns without any result boot auto configuration, at this point not knowing of any custom RepositoryFactoryBean definitions, kicks in, enabling repositories on fr.exemple.test where Application resides.
So you could update your package structure.
Or make boot aware of MyRepositoryFactoryBean by registering it in your context via #Component and remove #EnableMongoRepositories so that scanning for a bean of type RepositoryFactoryBeanSupport can pick up the config.
When you declare #EnableMongoRepositories please take a look at availables options. One of them is :
public abstract Class<?> repositoryFactoryBeanClass
Returns the FactoryBean class to be used for each repository instance.
Defaults to MongoRepositoryFactoryBean.
Returns:
Default:
org.springframework.data.mongodb.repository.support.MongoRepositoryFactoryBean.class
so i.e
#EnableMongoRepositories(repositoryFactoryBeanClass=YourMongoCustomRepositoryFactoryBean.class)

Resources