Error while creating bean with name "defaultServletHandlerMapping" - java

I am trying to run a spring boot application which uses annotation configuration, below is the WebConfig.java file,
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = {"com.kumar.codebuzz"})
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new SecurityHandlerInterceptor()).addPathPatterns("/v1/app/*").excludePathPatterns("/v1/generateOTP", "/v1/validateOTP", "/users/signUp");
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/swaggerui/**")
.addResourceLocations("classpath:/swaggerui/");
registry.addResourceHandler("/webview/**")
.addResourceLocations("classpath:/webview/");
}
#Bean
public ViewResolver configureViewResolver() {
InternalResourceViewResolver viewResolve = new InternalResourceViewResolver();
viewResolve.setPrefix("/WEB-INF/views/");
viewResolve.setSuffix(".jsp");
return viewResolve;
}
}
i am not able to start the application, below is the stack trace,
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultServletHandlerMapping' defined in class path resource [org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'defaultServletHandlerMapping' threw exception; nested exception is java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
not able to figure out the issue.
Thanks,

This would happen on below cases
1) #ComponentScan is not mentioned - This is not applicable in your case, since you have mentioned it in the WebMvcConfiguration class
2) #Configuration is used some where else in the same project - Check your project and find for #Configuration, if you have used it accidentally remove it.
There is also another way of removing it
Replace the #ComponentScan in your WebMvcConfiguration with the entry given below
#ComponentScan(basePackages = { "com.kumar.codebuzz" }, excludeFilters = { #Filter(type = FilterType.ANNOTATION, value = Configuration.class) })
References:
Error with Spring BOOT
Error creating bean with name 'defaultServletHandlerMapping
Error creating bean with name defaultServletHandlerMapping

Related

#WebMvcTest with #Autowire Constructor in WebConfig

I want to test a Spring RestController. There is a Web Config in this project with an #Autowired Constructor, which should initialize a ConfigurationPropertie with environment variables from the application-{environment}.yml-file. Since I have implemented this, my Application runs correctly but the WebMvcTest for the Controller is failing with following error:
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webConfig': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.project.onlineDate.shared.entity.OriginAllowedUrisProperties' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
Code Part 1: EnvironmentPropertie Class
#Configuration
#Component
#ConfigurationProperties(prefix = "origins")
public class OriginAllowedUrisProperties {
String[] allowedUris;
//Getter and Setter
}
Code Part 2: WebConfig
#Configuration
public class WebConfig implements WebMvcConfigurer {
private final
OriginAllowedUrisProperties originAllowedUrisProperties;
#Autowired
public WebConfig(OriginAllowedUrisProperties originAllowedUrisProperties) {
this.originAllowedUrisProperties = originAllowedUrisProperties;
}
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins(
originAllowedUrisProperties.getAllowedUris());
}
}
Code Part 3: WebMvcTest
#ExtendWith(SpringExtension.class)
#WebMvcTest(OnlineDateController.class)
class TestOnlineDateController {
[...]
#MockBean
private OnlineDateService onlineDateService;
#Autowired
private MockMvc mockMvc;
#Test
void testGetOnlineDate() throws Exception {
when(onlineDateService.findOnlineDates().thenReturn(
Collections.singletonList(new OnlineDate()));
mockMvc.perform(
get("/onlineDates")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(JSON_ONLINE_DATE_MATCHER)
.andDo(print());
}
}
Attemps for fix
I tried for example to declare a Context Configuration at Class Level with #ContextConfiguration(classes = {WebConfig.class}) and I´ve tried to exclude the configuration with #Filter declaration. I have also tried a lot with the OriginAllowedUrisProperties.class to load environment variables in another way, but nothing worked. What am I missing? Do you have an Idea? Thanks in advance.
After struggling to this I want to share my Solution. Hopefully this will help others who face the same challenge.After many attempts I have now solved it a bit differently.
My Solution:
I pulled the bean declaration out of the entity and made it directly in the web controller. This information is not needed anywhere else in the project and therefore I can leave all test classes as they are. Here are the code components, which I have changed in contrast to above.
Code Part 1: EnvironmentProperty Class
Removed Spring Annotations
public class OriginAllowedUrisProperties {
String[] allowedUris;
//Getter and Setter
}
Code Part 2: WebConfig
Bind the #ConfigurationProperties on a #Bean method in WebConfig to bind externalized properties to the OriginAllowedUrisProperties
#Configuration
public class WebConfig implements WebMvcConfigurer {
#Bean
#ConfigurationProperties(prefix = "origins")
public OriginAllowedUrisProperties originAllowedUrisProperties() {
return new OriginAllowedUrisProperties();
}
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins(originAllowedUrisProperties().getAllowedUris());
}
}

Register bean (with a custom bean name) programmatically

My goal is to register bean (with a custom bean name) programmatically.
#ComponentScan({ "com.test" })
public class AppConfiguration {
//#Bean("test-bean")
#Bean
public Definition definition() {
return () -> Test.class;
}
}
#Named
#Scope("prototype")
public class Test extends DefinitionActor<?> {
....
}
Here, I use Akka and hence I have to go with #Scope("prototype").
I don't want to hard code the bean name to test-bean for some reason.
Hence, I am using the BeanPostProcessor.
#Component
public class BeanDefinitionRegistryPP implements BeanDefinitionRegistryPostProcessor, EnvironmentAware {
private Environment env;
#Override
public void setEnvironment(final Environment environment) {
this.env = environment;
}
#Override
public void postProcessBeanDefinitionRegistry(final BeanDefinitionRegistry registry) throws BeansException {
}
I am getting AKKA error if I go with this way.
Caused by: akka.actor.ActorInitializationException: You cannot create an instance of [com.test.Test] explicitly using the constructor (new). You have to use one of the 'actorOf' factory methods to create a new actor. See the documentation.
at akka.actor.ActorInitializationException$.apply(Actor.scala:181) ~[akka-actor_2.11-2.4.19.jar:na]
The bean post processor work with non-Akka project. Is there any other way to set the bean name programmatically even I use prototype scope.

Getting no beans found errors when Custom Repo class extends with JpaRepository

I am creating a simple CRUD application using spring boot and hibernate with ajax requests from jsp page. i got working this to the controller and after when i extend my Repo class with JpaRepository i am geting no beans found errors.
i have tried to enable entity manager in web config class an then i also get no beans found for entity manager.
This is my controller class
#Controller
public class EmployeeController {
#Autowired
private EmployeeRepo employeeRepo;
#GetMapping("/")
public String employeeForm() {
return "employeeForm";
}
#PostMapping(value = "/saveEmployee", produces = { MediaType.APPLICATION_JSON_VALUE })
#ResponseBody
public boolean saveEmployee(#ModelAttribute #Valid Employee employee, BindingResult result) {
Employee save = employeeRepo.save(employee);
return true;
}
}
this is my custom repository
public interface EmployeeRepo extends JpaRepository<Employee,Integer> {
}
this is my web config class
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = { "com.boraji.tutorial.spring.controller" })
#ComponentScan(basePackages = { "com.boraji.tutorial.spring.repo" })
#EnableJpaRepositories(basePackages = "com.boraji.tutorial.spring.repo", entityManagerFactoryRef = "entityManagerFactory")
public class WebConfig extends WebMvcConfigurerAdapter {
#Bean
public InternalResourceViewResolver resolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setViewClass(JstlView.class);
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
#Bean
public HibernateExceptionTranslator hibernateExceptionTranslator(){
return new HibernateExceptionTranslator();
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
this is my webapp initializer class
public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] {};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { WebConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
this is the error
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'employeeController': Unsatisfied dependency expressed through field 'employeeRepo'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeRepo': Cannot create inner bean '(inner bean)#7dc21c89' of type
[org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#7dc21c89': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available

Spring boot : delegateBuilder cannot be null on autowiring authenticationManager in custom UserDetailsService

Hi i'm new to spring boot and trying implement the security to my rest apis.
i'm using spring boot 2.0.7.release
i have configures my WebSecurityConfig as following
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Resource(name = "userService")
private UserDetailsService userDetailsService;
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(encoder());
}
#Bean
public JwtAuthenticationFilter authenticationTokenFilterBean() throws Exception {
return new JwtAuthenticationFilter();
}
#Bean
public PasswordEncoder encoder(){
PasswordEncoder encoder = new CustomPasswordEncoder();
return encoder;
}
....
}
I have add the resource name so that i can point the to custom userDetailsService.
I have tried configuring authenticationManager Bean by came and pointing the bean by Qualifier authenticationManager bean still it the error remains same.
my pom.xml looks like for security
......
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
......
and my implemented UserServiceImpl is
#Service(value = "userService")
public class UserServiceImpl implements UserService, UserDetailsService {
#Autowired
private UserDAOService userDao;
#Autowired
private AuthenticationManager authenticationManager;
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userDao.findByUsername(username);
if(user == null){
throw new UsernameNotFoundException("Invalid username or password.");
}
return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), getAuthority());
}
#Override
public String login(LoginUser user) {
// valid user if it exits then do the following
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()));
//generate the token and do other process.
}
following are the error logs. i have provided only mail errors
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'webSecurityConfig': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService': Unsatisfied dependency expressed through field 'authenticationManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authenticationManager' defined in class path resource [com/saikrishna/security/config/WebSecurityConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.authentication.AuthenticationManager]: Circular reference involving containing bean 'webSecurityConfig' - consider declaring the factory method as static for independence from its containing instance. Factory method 'authenticationManagerBean' threw exception; nested exception is java.lang.IllegalArgumentException: delegateBuilder cannot be null
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService': Unsatisfied dependency expressed through field 'authenticationManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authenticationManager' defined in class path resource [com/saikrishna/security/config/WebSecurityConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.authentication.AuthenticationManager]: Circular reference involving containing bean 'webSecurityConfig' - consider declaring the factory method as static for independence from its containing instance. Factory method 'authenticationManagerBean' threw exception; nested exception is java.lang.IllegalArgumentException: delegateBuilder cannot be null
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authenticationManager' defined in class path resource [com/saikrishna/security/config/WebSecurityConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.authentication.AuthenticationManager]: Circular reference involving containing bean 'webSecurityConfig' - consider declaring the factory method as static for independence from its containing instance. Factory method 'authenticationManagerBean' threw exception; nested exception is java.lang.IllegalArgumentException: delegateBuilder cannot be null
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.authentication.AuthenticationManager]: Circular reference involving containing bean 'webSecurityConfig' - consider declaring the factory method as static for independence from its containing instance. Factory method 'authenticationManagerBean' threw exception; nested exception is java.lang.IllegalArgumentException: delegateBuilder cannot be null
Caused by: java.lang.IllegalArgumentException: delegateBuilder cannot be null
at org.springframework.util.Assert.notNull(Assert.java:193) ~[spring-core-5.0.11.RELEASE.jar:5.0.11.RELEASE]
In order to help you better, it is better if you indicate which reference you are following to implement JWT mechansim.
Conceptually, this part of the source code is wrong:
#Override
public String login(LoginUser user) {
// valid user if it exits then do the following
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()));
//generate the token and do other process.
}
See if the modifications below can help you
1) Consider using Java Config to declare your beans, in a seperate Configuration class
#Configuration
public class ServiceConfig{
#Bean
protected UserDAOService daoService()
{
return new UserDAOServiceImpl();
}
#Bean
protected UserDetailsService userDetailService( UserDAOService dao )
{
return new UserServiceImpl( dao );
}
#Bean
public PasswordEncoder encoder(){
PasswordEncoder encoder = new CustomPasswordEncoder();
return encoder;
}
#Bean
public JwtAuthenticationFilter authenticationTokenFilterBean() throws Exception{ {
return new JwtAuthenticationFilter();
}
}
2) Modification to your WebSecurityConfig
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailsService userDetailsService;
#Autowired
private PasswordEncoder passwordEncoder;
#Override
protected void configure( AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService( userDetailsService ).passwordEncoder( passwordEncoder );
}
}

How could I get #FeignClient bean when spring boot application initializing

I need use a bean inject with #Component #FeignClient(name = "xxx") when my spring boot application initializing, but it always throws exception like this:
20180706 10:18:40,043 WARN [main]
[org.springframework.context.annotation.AnnotationConfigApplicationContext]
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'feignContract' defined in org.springframework.cloud.netflix.feign.FeignClientsConfiguration: Unsatisfied dependency expressed through method 'feignContract' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'feignConversionService' defined in org.springframework.cloud.netflix.feign.FeignClientsConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.format.support.FormattingConversionService]: Factory method 'feignConversionService' threw exception; nested exception is java.lang.StackOverflowError
my feignClient code:
#Component
#FeignClient(name = "domain-account")
public interface IDomainService {
#RequestMapping(value = "/userInfos", method = RequestMethod.GET)
public String getUserInfos(#QueryMap Map<String, Object> condition);
}
ApplicationListenner code:
public class GlobalInit implements ApplicationListener<ContextRefreshedEvent> {
#Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
System.out.println("======== GlobalInit ========");
IDomainService domainService = contextRefreshedEvent.getApplicationContext().getBean(IDomainService.class);
System.out.println("*********************" + domainService);
GlobalInitManager.getInstance().doInit();
}
}
It's not entirely clear for me what you try to do with the GlobalInit but the 'standard' way of designing your Feign client in Spring Boot would the following:
#SpringBootApplication
#EnableFeignClients
#EnableHypermediaSupport(type = EnableHypermediaSupport.HypermediaType.HAL)
#EnableCaching
public class MyHelloWorldApplication {
public static void main(String[] args) {
SpringApplication.run(MyHelloWorldApplication.class, args);
}
}
#Component
public class HelloWorldServiceImpl implements HelloWorldService {
#Autowired
private IDomainService iDomainService ;
public void myMethod() {
String userinfo = iDomainService.getUserInfos(...);
}
}
Hopefully this helps.
All the best,
Wim

Categories