I want to read the integer value from the key which I defined in application.properties file. Here is my properties file.
spring.rabbitmq.port=31111
And here is the code:
public Object getPortProperty() {
Properties properties = new Properties();
try {
File file = ResourceUtils.getFile("classpath:application.properties");
InputStream in = new FileInputStream(file);
properties.load(in);
} catch (IOException e) {
}
return (Integer) properties.get("spring.rabbitmq.port");
}
#Autowired
public UnitAmqpRestController(RabbitTemplate rabbitTemplate) throws IOException, TimeoutException {
this.rabbitTemplate = rabbitTemplate;
rabbitTemplate.setReplyTimeout(15_000L);
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(getHostProperty());
factory.setPort((Integer) getPortProperty());
connection = factory.newConnection();
channel = connection.createChannel();
}
Getting the following error:
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'unitAmqpRestController' defined in URL
[jar:file:/tmp/unitamqpservice-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/com/abc/ci/unitamqpservice/UnitAmqpRestController.class]:
Bean instantiation via constructor failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate
[com.abc.ci.unitamqpservice.UnitAmqpRestController$$EnhancerBySpringCGLIB$$e7ff3f42]:
Constructor threw exception; nested exception is
java.lang.NullPointerException
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:279)
~[spring-beans-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1193)
~[spring-beans-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1095)
~[spring-beans-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
~[spring-beans-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
~[spring-beans-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
~[spring-beans-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
~[spring-beans-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
~[spring-beans-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
~[spring-beans-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
~[spring-beans-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
~[spring-context-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
~[spring-context-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
~[spring-boot-1.5.10.RELEASE.jar!/:1.5.10.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
[spring-boot-1.5.10.RELEASE.jar!/:1.5.10.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360)
[spring-boot-1.5.10.RELEASE.jar!/:1.5.10.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
[spring-boot-1.5.10.RELEASE.jar!/:1.5.10.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118)
[spring-boot-1.5.10.RELEASE.jar!/:1.5.10.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107)
[spring-boot-1.5.10.RELEASE.jar!/:1.5.10.RELEASE]
at com.abc.ci.unitamqpservice.UnitamqpserviceApplication.main(UnitamqpserviceApplication.java:10)
[classes!/:0.0.1-SNAPSHOT]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_212]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
~[na:1.8.0_212]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
~[na:1.8.0_212]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_212]
at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48)
[unitamqpservice-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.boot.loader.Launcher.launch(Launcher.java:87)
[unitamqpservice-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.boot.loader.Launcher.launch(Launcher.java:50)
[unitamqpservice-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:51)
[unitamqpservice-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT] Caused by:
org.springframework.beans.BeanInstantiationException: Failed to
instantiate
[com..ci.unitamqpservice.UnitAmqpRestController$$EnhancerBySpringCGLIB$$e7ff3f42]:
Constructor threw exception; nested exception is
java.lang.NullPointerException
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:154)
~[spring-beans-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:122)
~[spring-beans-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:271)
~[spring-beans-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]
... 26 common frames omitted Caused by: java.lang.NullPointerException: null
at com.abc.ci.unitamqpservice.UnitAmqpRestController.(UnitAmqpRestController.java:75)
~[classes!/:0.0.1-SNAPSHOT]
at com.abc.ci.unitamqpservice.UnitAmqpRestController$$EnhancerBySpringCGLIB$$e7ff3f42.()
~[classes!/:0.0.1-SNAPSHOT]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
~[na:1.8.0_212]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
~[na:1.8.0_212]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
~[na:1.8.0_212]
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
~[na:1.8.0_212]
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:142)
~[spring-beans-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]
... 28 common frames omitted
I am not able to understand why it is not working with the integer. if I have a string value, it works perfectly.
please suggest what is wrong in the code
The problematic line of the code is:
factory.setPort((Integer) getPortProperty());
Your code is throwing a NullPointerException and you have an empty catch block. At the bare minimum you should add some logging in there to see what's happening.
Also, you're using Spring and should rarely need to parse application.properties manually; it automatically gets loaded into the application environment.
So you can use #Value to bind it to a local variable instead (same for host property):
#Value("${spring.rabbitmq.port}")
private int mqPort;
#Value("${spring.rabbitmq.host}")
private String mqHost;
#Autowired
public UnitAmqpRestController(RabbitTemplate rabbitTemplate) throws IOException, TimeoutException {
this.rabbitTemplate = rabbitTemplate;
rabbitTemplate.setReplyTimeout(15_000L);
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(mqHost);
factory.setPort(mqPort);
connection = factory.newConnection();
channel = connection.createChannel();
}
Additionally, you should consider using the Spring Boot Rabbit MQ starter module to manage your Rabbit MQ connections and properties instead of managing it yourself.
Having spring.rabbitmq.port=31111 in application.properties or yml, read it using the #Value annotation which reads the property and parses to a correct type:
#Value("${spring.rabbitmq.port=31111}")
private int port;
The class itself should be recognizable as a bean using either #Configuration or any variation of #Component such as #Service.
If you want to load a property using a method as you do, consider using a special method for the integers:
private int getIntegerProperty(final String key, final int defaultValue) {
final Object object = properties.get("spring.rabbitmq.port")
if (object == null || "".equals(object.toString())) {
return defaultValue;
} else {
return Integer.parseInt(object );
}
}
Related
When I use spring security in springboot, I got an error.
Then I google it, I still can't resolve it.
Then I refer to the spring document(It's easy), I did the configuration, I still have a problem.
here is my error:
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: key cannot be empty or null
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:296) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at cn.edu.jit.email.EmailApplication.main(EmailApplication.java:38) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_144]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_144]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_144]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_144]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-1.5.9.RELEASE.jar:1.5.9.RELEASE]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalArgumentException: key cannot be empty or null
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
... 25 common frames omitted
Caused by: java.lang.IllegalArgumentException: key cannot be empty or null
at org.springframework.util.Assert.hasLength(Assert.java:157) ~[spring-core-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices.<init>(AbstractRememberMeServices.java:89) ~[spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices.<init>(TokenBasedRememberMeServices.java:87) ~[spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.config.annotation.web.configurers.RememberMeConfigurer.createTokenBasedRememberMeServices(RememberMeConfigurer.java:395) ~[spring-security-config-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.config.annotation.web.configurers.RememberMeConfigurer.createRememberMeServices(RememberMeConfigurer.java:381) ~[spring-security-config-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.config.annotation.web.configurers.RememberMeConfigurer.getRememberMeServices(RememberMeConfigurer.java:346) ~[spring-security-config-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.config.annotation.web.configurers.RememberMeConfigurer.init(RememberMeConfigurer.java:269) ~[spring-security-config-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.config.annotation.web.configurers.RememberMeConfigurer.init(RememberMeConfigurer.java:80) ~[spring-security-config-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.init(AbstractConfiguredSecurityBuilder.java:371) ~[spring-security-config-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.doBuild(AbstractConfiguredSecurityBuilder.java:325) ~[spring-security-config-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.config.annotation.AbstractSecurityBuilder.build(AbstractSecurityBuilder.java:41) ~[spring-security-config-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.config.annotation.web.builders.WebSecurity.performBuild(WebSecurity.java:290) ~[spring-security-config-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.config.annotation.web.builders.WebSecurity.performBuild(WebSecurity.java:77) ~[spring-security-config-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.doBuild(AbstractConfiguredSecurityBuilder.java:334) ~[spring-security-config-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.config.annotation.AbstractSecurityBuilder.build(AbstractSecurityBuilder.java:41) ~[spring-security-config-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain(WebSecurityConfiguration.java:104) ~[spring-security-config-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$d5f876d6.CGLIB$springSecurityFilterChain$6(<generated>) ~[spring-security-config-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$d5f876d6$$FastClassBySpringCGLIB$$784debf.invoke(<generated>) ~[spring-security-config-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$d5f876d6.springSecurityFilterChain(<generated>) ~[spring-security-config-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_144]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_144]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_144]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_144]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
... 26 common frames omitted
here is my application
#SpringBootApplication
#ComponentScan("cn.edu.jit.email")
#EnableTransactionManagement
#MapperScan("cn.edu.jit.email.mapper")
public class EmailApplication extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(EmailApplication.class);
}
#Bean
public PlatformTransactionManager txManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
public static void main(String[] args) {
SpringApplication.run(EmailApplication.class, args);
}
}
here is my security config:
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Bean
UserDetailsService customUserService() {
return new CustomUserService();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/**").access("hasRole('ROLE_USER')")
.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
.anyRequest().authenticated().and()
.rememberMe().tokenValiditySeconds(60 * 60 * 24 * 7).key("").and()
.formLogin().loginPage("/login").failureUrl("/login?error").permitAll().and()
.logout().permitAll();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserService());
}
}
here is CustomUserService
#Service
public class CustomUserService implements UserDetailsService {
#Autowired
private UserService userService;
#Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
System.out.println("loaduser " + s);
User user = userService.getUserByUsername(s);
if (user == null || user.getIsDel() == 1) {
throw new UsernameNotFoundException("用户不存在或已被删除");
}
List<GrantedAuthority> auths = new ArrayList<>();
for (Role role : user.getRoles()) {
auths.add(new SimpleGrantedAuthority(role.getName()));
}
System.out.println("load finish");
return new org.springframework.security.core.userdetails.User(s, user.getPwd(), auths);
}
}
here is security's dependency in pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
The culprit is key("") in line .rememberMe().tokenValiditySeconds(60 * 60 * 24 * 7).key(""). Since spring security requires a key for generating encrypted tokens, try passing a non-empty value for a key.
I created a very simple exception in my Spring Boot application:
package tech.dashman.server.controllers.support;
public class BadRequestException extends Exception {
public BadRequestException(String message) {
super(message);
}
}
and I'm trying to turn it into a BAD_REQUEST in my ControllerAdvice that looks like this:
#ControllerAdvice
public class RestExceptionHandler {
// Other handlers that just work
#ExceptionHandler(BadRequestException.class)
public ResponseEntity<?> handleValidationError(BadRequestException ex, HttpServletRequest request) {
return new ResponseEntity<>(null, null, HttpStatus.BAD_REQUEST);
}
}
When I start the application, it crashes with this message:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'handlerExceptionResolver' defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerExceptionResolver]: Factory method 'handlerExceptionResolver' threw exception; nested exception is java.lang.IllegalStateException: Ambiguous #ExceptionHandler method mapped for [class org.springframework.web.bind.MethodArgumentNotValidException]: {public org.springframework.http.ResponseEntity tech.dashman.server.controllers.support.RestExceptionHandler.handleValidationError(org.springframework.web.bind.MethodArgumentNotValidException,javax.servlet.http.HttpServletRequest), public final org.springframework.http.ResponseEntity org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler.handleException(java.lang.Exception,org.springframework.web.context.request.WebRequest)}
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) ~[spring-context-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at tech.dashman.server.DashmanServerApplication.main(DashmanServerApplication.java:13) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_144]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_144]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_144]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_144]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-1.5.6.RELEASE.jar:1.5.6.RELEASE]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerExceptionResolver]: Factory method 'handlerExceptionResolver' threw exception; nested exception is java.lang.IllegalStateException: Ambiguous #ExceptionHandler method mapped for [class org.springframework.web.bind.MethodArgumentNotValidException]: {public org.springframework.http.ResponseEntity tech.dashman.server.controllers.support.RestExceptionHandler.handleValidationError(org.springframework.web.bind.MethodArgumentNotValidException,javax.servlet.http.HttpServletRequest), public final org.springframework.http.ResponseEntity org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler.handleException(java.lang.Exception,org.springframework.web.context.request.WebRequest)}
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
... 23 common frames omitted
Caused by: java.lang.IllegalStateException: Ambiguous #ExceptionHandler method mapped for [class org.springframework.web.bind.MethodArgumentNotValidException]: {public org.springframework.http.ResponseEntity tech.dashman.server.controllers.support.RestExceptionHandler.handleValidationError(org.springframework.web.bind.MethodArgumentNotValidException,javax.servlet.http.HttpServletRequest), public final org.springframework.http.ResponseEntity org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler.handleException(java.lang.Exception,org.springframework.web.context.request.WebRequest)}
at org.springframework.web.method.annotation.ExceptionHandlerMethodResolver.addExceptionMapping(ExceptionHandlerMethodResolver.java:109) ~[spring-web-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.web.method.annotation.ExceptionHandlerMethodResolver.<init>(ExceptionHandlerMethodResolver.java:76) ~[spring-web-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver.initExceptionHandlerAdviceCache(ExceptionHandlerExceptionResolver.java:269) ~[spring-webmvc-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver.afterPropertiesSet(ExceptionHandlerExceptionResolver.java:245) ~[spring-webmvc-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.addDefaultHandlerExceptionResolvers(WebMvcConfigurationSupport.java:883) ~[spring-webmvc-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration.configureHandlerExceptionResolvers(WebMvcAutoConfiguration.java:450) ~[spring-boot-autoconfigure-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.handlerExceptionResolver(WebMvcConfigurationSupport.java:826) ~[spring-webmvc-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration$$EnhancerBySpringCGLIB$$fa3dc8d5.CGLIB$handlerExceptionResolver$31(<generated>) ~[spring-boot-autoconfigure-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration$$EnhancerBySpringCGLIB$$fa3dc8d5$$FastClassBySpringCGLIB$$1ee68c67.invoke(<generated>) ~[spring-boot-autoconfigure-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358) ~[spring-context-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration$$EnhancerBySpringCGLIB$$fa3dc8d5.handlerExceptionResolver(<generated>) ~[spring-boot-autoconfigure-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_144]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_144]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_144]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_144]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
... 24 common frames omitted
which I'm having trouble understanding. What's going on? What's the correct way of doing this?
The other handlers look like this:
#ControllerAdvice
public class RestExceptionHandler {
#ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<?> handleValidationError(MethodArgumentNotValidException manve, HttpServletRequest request) {
ErrorDetail errorDetail = getErrorDetail(manve);
errorDetail.setStatus(HttpStatus.BAD_REQUEST.value());
errorDetail.setTitle(ErrorDetail.VALIDATION_FAILED);
errorDetail.setDetail("Input validation failed");
errorDetail.addFieldErrors(manve.getBindingResult().getFieldErrors());
return new ResponseEntity<>(errorDetail, null, HttpStatus.BAD_REQUEST);
}
#ExceptionHandler(NotFoundException.class)
public ResponseEntity<?> handleNotFoundException(MethodArgumentNotValidException manve, HttpServletRequest request) {
ErrorDetail errorDetail = getErrorDetail(manve);
errorDetail.setStatus(HttpStatus.NOT_FOUND.value());
errorDetail.setTitle("Not Found");
errorDetail.setDetail("Resource not found");
return new ResponseEntity<>(errorDetail, null, HttpStatus.NOT_FOUND);
}
private ErrorDetail getErrorDetail(MethodArgumentNotValidException manve) {
ErrorDetail errorDetail = new ErrorDetail();
errorDetail.setTimeStamp(new Date().getTime());
errorDetail.setDeveloperMessage(manve.getClass().getName());
return errorDetail;
}
#ExceptionHandler(BadRequestException.class)
public ResponseEntity<?> handleValidationError(BadRequestException ex, HttpServletRequest request) {
return new ResponseEntity<>(null, null, HttpStatus.BAD_REQUEST);
}
}
Here I have AmazonService class which contains ec2 object,
import org.springframework.stereotype.Component;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2ClientBuilder;
#Component
public class AmazonService {
private AmazonEC2 ec2 = AmazonEC2ClientBuilder.standard().withRegion(Regions.AP_SOUTH_1).build();
public AmazonEC2 getEc2() {
return ec2;
}
}
I need to get this ec2 from a service class as follows,
#Service
public class SecurityGroupServiceImpl implements SecurityGroupService {
#Autowired
AmazonService amazonService;
final AmazonEC2 ec2 = amazonService.getEc2();
#Override
public DeleteSecurityGroupResult deleteSecurityGroup(SecurityGroupDTO securityGroupDTO) {
DeleteSecurityGroupRequest request = new DeleteSecurityGroupRequest()
.withGroupId(securityGroupDTO.getGroupID());
DeleteSecurityGroupResult response = ec2.deleteSecurityGroup(request);
System.out.println(response);
return response;
}
}
My Controller class is as follows,
#Controller
public class SecurityGroupController {
#Autowired
SecurityGroupService service;
#RequestMapping(value = "/deleteSecurityGroup", produces = "application/json",
consumes = "application/json", method = RequestMethod.POST)
private #ResponseBody DeleteSecurityGroupResult deleteSecurityGroup(#RequestBody SecurityGroupDTO securityGroupDTO){
return service.deleteSecurityGroup(securityGroupDTO);
}
}
When I tried to run this I am getting error as,
Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-06-28 18:46:21.213 ERROR 7792 --- [ main] o.s.boot.SpringApplication : Application startup failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityGroupController': Unsatisfied dependency expressed through field 'service'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityGroupServiceImpl' defined in file [E:\Project\AWS-SDK-Implimentation\target\classes\com\altimetrik\services\impl\SecurityGroupServiceImpl.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.altimetrik.services.impl.SecurityGroupServiceImpl]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
at com.altimetrik.AwsSdkImplimentationApplication.main(AwsSdkImplimentationApplication.java:10) [classes/:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityGroupServiceImpl' defined in file [E:\Project\AWS-SDK-Implimentation\target\classes\com\altimetrik\services\impl\SecurityGroupServiceImpl.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.altimetrik.services.impl.SecurityGroupServiceImpl]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1155) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1099) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
... 19 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.altimetrik.services.impl.SecurityGroupServiceImpl]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:154) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1147) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
... 30 common frames omitted
Caused by: java.lang.NullPointerException: null
at com.altimetrik.services.impl.SecurityGroupServiceImpl.<init>(SecurityGroupServiceImpl.java:35) ~[classes/:na]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_121]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_121]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_121]
at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_121]
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:142) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
... 32 common frames omitted
Here I am using ec2 object in various service class, so I don't want to initialize this every time in all the service class. Instead I need to create ec2 in separate class and consume it in all other service classes. But I am getting the above mentioned error on trying this. Someone help me out in fixing this issue.
Even better, why not take advantage of Java config (perfect for instantiating beans from third parties) and just have the AmazonEC2 as an actual Spring bean.
#Configuration
public class AmazonServiceConfiguration {
#Bean
public AmazonEC2 ec2() {
return AmazonEC2ClientBuilder.standard()
.withRegion(Regions.AP_SOUTH_1).build();
}
}
And your service implementation:
#Service
public class SecurityGroupServiceImpl implements SecurityGroupService {
#Autowired
AmazonEC2 ec2;
#Override
public DeleteSecurityGroupResult deleteSecurityGroup(SecurityGroupDTO securityGroupDTO) {
DeleteSecurityGroupRequest request = new DeleteSecurityGroupRequest()
.withGroupId(securityGroupDTO.getGroupID());
DeleteSecurityGroupResult response = ec2.deleteSecurityGroup(request);
System.out.println(response);
return response;
}
}
Here when you try to set ec2 from SecurityGroupServiceImpl class, which is not actually created at the time by AmazonService class. So try to get ec2 in SecurityGroupServiceImpl after loading AmazonService class
When SecurityGroupServiceImpl is created there is no amazonService. It's autowired later so the attempt to get something produces NPE.
Instead move the init in #PostConstruct
#PostConstruct
public void init() throws Exception {
ec2 = amazonService.getEc2();
}
Of course the field should not be final.
Alternatively remove the #Autowire from field and move to constructor and initialize the final field from the constructor (Read #Autowired on Constructors section here https://www.tutorialspoint.com/spring/spring_autowired_annotation.htm )
i have a very basic program but no matter what I change in the code I always get the same Error Message:
Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-05-29 17:03:01.228 ERROR 6260 --- [ main] o.s.boot.SpringApplication : Application startup failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoApplication': Unsatisfied dependency expressed through field 'queryRepoImp'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'queryRepoImp' defined in file [C:\Dropbox\Projects\h2TestEnv\target\classes\com\example\demo\QueryRepoImp.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.example.demo.QueryRepoImp]: Constructor threw exception; nested exception is java.util.MissingResourceException: Can't find com.example.demo.QueryRepoImp bundle
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866) ~[spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) ~[spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
at com.example.demo.DemoApplication.main(DemoApplication.java:21) [classes/:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'queryRepoImp' defined in file [C:\Dropbox\Projects\h2TestEnv\target\classes\com\example\demo\QueryRepoImp.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.example.demo.QueryRepoImp]: Constructor threw exception; nested exception is java.util.MissingResourceException: Can't find com.example.demo.QueryRepoImp bundle
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1155) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1099) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
... 19 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.example.demo.QueryRepoImp]: Constructor threw exception; nested exception is java.util.MissingResourceException: Can't find com.example.demo.QueryRepoImp bundle
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:154) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1147) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
... 30 common frames omitted
Caused by: java.util.MissingResourceException: Can't find com.example.demo.QueryRepoImp bundle
at java.util.logging.Logger.setupResourceInfo(Logger.java:1946) ~[na:1.8.0_131]
at java.util.logging.Logger.<init>(Logger.java:380) ~[na:1.8.0_131]
at java.util.logging.LogManager.demandLogger(LogManager.java:554) ~[na:1.8.0_131]
at java.util.logging.Logger.demandLogger(Logger.java:455) ~[na:1.8.0_131]
at java.util.logging.Logger.getLogger(Logger.java:553) ~[na:1.8.0_131]
at com.example.demo.QueryRepoImp.<init>(QueryRepoImp.java:17) ~[classes/:na]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_131]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_131]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_131]
at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_131]
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:142) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
... 32 common frames omitted
Process finished with exit code 1
My code:
#SpringBootApplication
public class DemoApplication {
private static final Logger log = LoggerFactory.getLogger(DemoApplication.class);
#Autowired
private ApplicationContext context;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#Autowired
QueryRepoImp queryRepoImp;
#Bean
public CommandLineRunner clr() {
return a -> {
/*
System.out.println("Create Queries");
Query c1 = new Query("Wood");
Query c2 = new Query("Stones");
// insert
repo.add(c1);
repo.add(c2);
for (Query t : repo.findAll()) {
System.out.println("Query: " + t.getRelation());
}
*/
};
}
}
QueryRepoImp.java
#Repository
public class QueryRepoImp implements QueryIRepoInt {
private final String SQL_INSERT = "INSERT INTO query (section) VALUES (?)";
private final String SQL_FINDALL = "SELECT * FROM query ORDER BY lastname";
Logger logger = Logger.getLogger("QueryLogger", QueryRepoImp.class.getName());
#Autowired
JdbcOperations jdbcTemplate;
#Override
public void add(Query query) {
Object[] objects = {query};
List<Object[]> list = new LinkedList<>();
list.add(objects);
jdbcTemplate.batchUpdate(SQL_INSERT, list);
}
}
QueryIRepoInt.java
#Component
public interface QueryIRepoInt {
void add(Query query);
}
Can someone tell me please where the error hides? Thank you!
Please use following tags in your DemoApplication class.
#EnableTransactionManagement
#EnableAutoConfiguration
#ComponentScan({"Packages you want to scan"})
#EnableJpaRepositories("Repository package")
#SpringBootApplication
public class DemoApplication
{
/*Main method*/
}
Read the stacktrace carefully. The cause of your problem is written there.
Caused by: java.util.MissingResourceException: Can't find com.example.demo.QueryRepoImp bundle
This resource-bundle is missing. Check if it is part of your project and recheck. (Or you want to use the LoggerFactory to get a logger instance.)
If you have nested exceptions like this, please check every exception.
I am implementing a JMS client for a RabbitMQ server and I have the following Spring Boot config class.
#Configuration
public class JmsConfig {
private static String EXCHANGE_NAME = "exchange";
#Autowired
private ConnectionFactory connectionFactory;
#Bean
RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
return new RabbitAdmin(connectionFactory);
}
#Bean
Queue queue(RabbitAdmin rabbitAdmin) {
return rabbitAdmin.declareQueue();
}
#Bean
FanoutExchange exchange() {
return new FanoutExchange(EXCHANGE_NAME);
}
#Bean
Binding binding(Queue queue, FanoutExchange exchange) {
Binding binding = BindingBuilder.bind(queue).to(exchange);
return binding;
}
}
Highlight that in the RabbitMQ server the exchange already exists but the queue connected to the exchange should be created dinamycally by the client(that's the intention) when I run it.
When I start the client app I get the following stacktrace:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'queue' defined in class path resource [com/optimusbet/jms/JmsConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.amqp.core.Queue]: Factory method 'queue' threw exception; nested exception is org.springframework.amqp.UncategorizedAmqpException: java.lang.IllegalStateException: Invalid configuration: 'exchange' must be non-null.
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866) ~[spring-context-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) ~[spring-context-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at com.optimusbet.OptimusbetSportsClientApiApplication.main(OptimusbetSportsClientApiApplication.java:20) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_45]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_45]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_45]
at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_45]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-1.5.1.RELEASE.jar:1.5.1.RELEASE]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.amqp.core.Queue]: Factory method 'queue' threw exception; nested exception is org.springframework.amqp.UncategorizedAmqpException: java.lang.IllegalStateException: Invalid configuration: 'exchange' must be non-null.
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
... 23 common frames omitted
Caused by: org.springframework.amqp.UncategorizedAmqpException: java.lang.IllegalStateException: Invalid configuration: 'exchange' must be non-null.
Any ideas of what's going wrong in the initialization? Thanks in advance.
You don't need to declare the queue with the admin - and in fact you should never interact with the broker in a bean definition. The context is not fully baked yet.
You just need...
#Bean
Queue queue() {
return new AnonymousQueue();
}
... you can't use broker-named queues here.
Also, this is not a "JMS" client, it's a RabbitMQ client.
EDIT
#SpringBootApplication
public class So42328067Application {
private static final String FANOUT = "fanout";
private static final String QUEUE = "foo";
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext context = SpringApplication.run(So42328067Application.class, args);
context.getBean(RabbitTemplate.class).convertAndSend(FANOUT, "", "bar");
Thread.sleep(5000);
context.close();
}
#Bean
public Queue queue() {
return new Queue(QUEUE);
}
#Bean
public FanoutExchange exchange() {
return new FanoutExchange(FANOUT);
}
#Bean
public Binding binding() {
return BindingBuilder.bind(queue()).to(exchange());
}
#RabbitListener(queues = QUEUE)
public void listen(String in) {
System.out.println(in);
}
}