Is there a way to do this in spring mvc; I want to #Autowired RedirectAttributes:
#Controller
public class RegistrationController {
#Autowired private RedirectAttributes redirectAttributes;
#RequestMapping(value = SIGNUP_ROUTE, method = RequestMethod.POST)
public String signUpPage(ModelMap modelMap, User user) {
save(user);
redirectAttributes.addFlashAttribute("success", "Very good");
return "redirect:/sign-in";
}
}
Exception I get:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'registrationController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.web.servlet.mvc.support.RedirectAttributes com.myhome.controller.RegistrationController.redirectAttributes; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.web.servlet.mvc.support.RedirectAttributes] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
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)
One way to inject the dependency in your code could be adding an extra parameter of the class RedirectAttributes
#Controller
public class RegistrationController {
#RequestMapping(value = SIGNUP_ROUTE, method = RequestMethod.POST)
public String signUpPage(ModelMap modelMap, RedirectAttributes rda, User user) {
save(user);
rda.addFlashAttribute("success", "Very good");
return "redirect:/sign-in";
}
}
Related
Dear fellow programmers,
The context is the next: The user, after completing the registration form and send, be authenticated and redirected to the home page automatically, not having to return to the login form to log in.
The application security is managed by Spring Security.
I'm trying to implement this new function in my application, but it does not work.
I have problem especifcally to inject the authenticationManager in my SpringService, look bellow my code:
Class SignUpMB:
#RequestScope
#Component
public class SignUpMB {
#Autowired
private UserService userService;
#Autowired
private SignupService signUpService;
private User user = new User();
private ProfileUser profileUser = new ProfileUser();
private String confirmPw;
#RequestMapping(value = "/account/signup", method = RequestMethod.POST)
public String createNewUser(#ModelAttribute("user") User user, BindingResult result, HttpServletRequest request, HttpServletResponse response) {
userService.addUser(user, profileUser);
signUpService.authenticateUserAndSession(user, request);
return "../index.xhtml";
}
...
}
Class SignupService:
#Service
public class SignupService {
#Autowired
protected AuthenticationManager authenticationManager;
/*#Autowired
RequestCache requestCache;*/
public void authenticateUserAndSession(User user, HttpServletRequest request) {
String username = user.getMail();
String password = user.getPassword();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
request.getSession();
token.setDetails(new WebAuthenticationDetails(request));
Authentication authenticationUser= authenticationManager.authenticate(token);
SecurityContextHolder.getContext().setAuthentication(authenticationUser);
}
}
Now follow the error:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'signupService': Unsatisfied dependency expressed through field 'authenticationManager': No qualifying bean of type [org.springframework.security.authentication.AuthenticationManager] found for dependency [org.springframework.security.authentication.AuthenticationManager]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.authentication.AuthenticationManager] found for dependency [org.springframework.security.authentication.AuthenticationManager]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:573)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:350)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
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:775)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4790)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5256)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1420)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1410)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.authentication.AuthenticationManager] found for dependency [org.springframework.security.authentication.AuthenticationManager]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1398)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1051)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1018)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:570)
... 24 more
Please, any idea how I can solved it? Thank you so mutch.
Override authenticationManagerBean() method of WebSecurityConfigurerAdapter to manually expose AuthenticationManager as a spring bean.
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Bean(name = BeanIds.AUTHENTICATION_MANAGER)
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
You only can autowire spring managed bean.
I'm trying to use JPA for my spring application. I have integrated the JPATransactionManager & LocalEntityManagerFactoryBean into AppConfig class. Now, when I try to call one of the method which is in DaoImpl, the AppConfig is not able to Autowire the classes. Here is my code
Test Class
public class Test {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class);
BbDao personService = context.getBean(BbDao.class);
personService.getDealByDealId("0194541605021NJMAPFU");
context.close();
}
}
AppConfig
#Configuration
#EnableWebMvc
#EnableTransactionManagement
#ComponentScan(basePackages = "net.bb.spring")
public class AppConfig{
#Bean
public LocalEntityManagerFactoryBean getEntityManagerFactoryBean() {
LocalEntityManagerFactoryBean factoryBean = new LocalEntityManagerFactoryBean();
factoryBean.setPersistenceUnitName("MyPersistence");
return factoryBean;
}
#Bean
public JpaTransactionManager geJpaTransactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(getEntityManagerFactoryBean().getObject());
return transactionManager;
}
}
ConfirmPurchaseController
#RestController
public class ConfirmPurchaseController {
private Logger logger = Logger.getLogger(ConfirmPurchaseController.class);
#Autowired
private MyService myService;
#GetMapping("/purchase")
public ResultDto confirmpurchase(HttpServletResponse response) throws ClassNotFoundException, IOException {
// Business Logic
}
}
MyService
#Component
public interface MyService {
// Methods defined
}
MyServiceImpl
#Service
public class MyServiceImpl implements MyService, ServletContextAware {
private ServletContext servletContext;
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
public ServletContext getServletContext() {
return servletContext;
}
// Added the implemented methods of the MyService Interface
}
The exception it throws is
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myServiceImpl': Unsatisfied dependency expressed through field 'servletContext'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.servlet.ServletContext' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
and the error log is
Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'confirmPurchaseController': Unsatisfied dependency expressed through field 'myService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myServiceImpl': Unsatisfied dependency expressed through field 'servletContext'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.servlet.ServletContext' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
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:761)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:84)
at net.bb.spring.controller.Test.main(Test.java:14)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myServiceImpl': Unsatisfied dependency expressed through field 'servletContext'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.servlet.ServletContext' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
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:202)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
... 14 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.servlet.ServletContext' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1493)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
... 27 more
Any ideas would be very helpful for me.
P.S : Im using configuration as annotations, no XML
It is not an answer, however I cannot add a comment yet.
Did you try to autowire a ServletContext via setter method?
- remove #Autowired from property
- remove one of your setters for context (unnecessary duplication)
- mark a setter as #Autowired
Moreover remove #Component annotation from MyService, it is unnecessary if you are using #Service annotation in its implementation.
As per Apache Tomcat documentation, a ServletContext
Defines a set of methods that a servlet uses to communicate with its
servlet container.
There is one context per "web application" per Java Virtual Machine.
(A "web application" is a collection of servlets and content installed
under a specific subset of the server's URL namespace such as /catalog
and possibly installed via a .war file.)
Which means that a ServletContext is only valid within a Servlet Container like Apache Tomcat. But as I can see, you are trying to run a normal Java application by creating beans in a main method, which makes the existence of ServletContext invalid.
So what you have to do is:
STEP 1: Build your AppConfig and override required methods.
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = {"net.bb.spring"})
public class AppConfig extends WebMvcConfigurerAdapter {
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/WEB-INF/");
}
//....
}
STEP 2: Create WebInitializer to initialize Dispatcher Servlet
public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] {AppConfig.class};
}
#Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
}
STEP 3: Create your Service layer to autowire ServletContext
#Service
public class MyServiceImpl implements MyService {
private ServletContext servletContext;
#Autowire
public MyServiceImpl(ServletContext servletContext) {
this.servletContext = servletContext;
}
public ServletContext getServletContext() {
return servletContext;
}
//...
}
STEP 4: Build your application to a WAR file
STEP 5: Deploy your WAR file to webapp folder of Tomcat (If you are using Tomcat)
STEP 6: Start Tomcat
Here is what you need to change:
1) You don't need to annotate the interface with #Component, annotation is required only on the implementation class
MyService
public interface MyService {
// Methods defined
}
2) Use constructor injection to obtain an instance of ServeletContext.
#Service
public class MyServiceImpl implements MyService, ServletContextAware {
private ServletContext servletContext;
#Autowire
public MyServiceImpl(ServletContext servletContext) {
this.servletContext = servletContext;
}
//TODO: other methods goes here...
}
pay attention that ServletContext is not a Spring bean and it can, therefore, not be injected unless you implement ServletContextAware. keep your implementation class implements ServletContextAware
i have below code.
Interface
#Component
public interface Service {
public String getConfig();
}
2 implementation
#Service("UserService")
public class userService implements Service{
#Override
public String getConfig() {
// logic goes here
return "result";
}
}
customer implementation
#Service("CustomerService")
public class userService implements Service{
#Override
public String getConfig() {
// logic goes here
return "result";
}
}
I have a configuration class where i need the bean dynamically
#Configuration
public class MyConfig {
#Autowired
ApplicationContext context;
#Bean
public Service getConfigBean(final String configName) {
Service service = (Service) context.getBean(configName);
return service;
}
}
from my controller/any other class i just want get the bean object
#RestController
#RequestMapping("/user")
#Scope(value = WebApplicationContext.SCOPE_REQUEST)
public class UserController {
#Autowired
MyConfig myConfig;
#Autowired
Service service;
#RequestMapping(produces = MediaType.TEXT_HTML , method = RequestMethod.GET)
public String getInitiate()
{
service = stateConversationConfig.getConfigBean("UserService"); // will get this String dynamically or based on logic
System.out.println("service object : "+service);
return "ok";
}
}
But when i run my application on tomcat, its failed to deploy with following exception
SEVERE: Application startup failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'getConfigBean' defined in class path resource [xxx/xxx/xxx/xxxxx.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [java.lang.String]: : No qualifying bean of type [java.lang.String] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.String] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:464)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1119)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1014)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
at xx.xxx.xxxx.xxx.xxx.main(Application.java:36)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.String] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1301)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1047)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:813)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
Am I doing something wrong.?
Beans are objects managed by Spring IoC container. When application context is created, beans are constructed, but Spring cannot create your configBean as it does not know what value should be passed to configName.
If you want dynamic services, I suggest that you create 2 separate beans (userServices and customerService) and a normal function (not with #Bean) getConfigBean(String configName).
I am new to Spring and I am try to make a application for learning but I am getting problem in Autowiring,I am adding my code. I am working on spring boot.
Spring Boot Code
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
LoginBean.java
#Service
#Component
public class LoginBean {
private String userId;
private String pwd;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
DemoRestController.java
#RestController
#EnableAutoConfiguration
#RequestMapping("/demo")
#Component
public class DemoRestController {
private final LoginBean loginBean;
#Autowired
public DemoRestController(LoginBean loginBean) {
this.loginBean=loginBean;
}
#RequestMapping(value = "/login/{id},{pwd}", method = RequestMethod.GET, produces = "application/json")
public #ResponseBody LoginBean loginService(#PathVariable String id, #PathVariable String pwd) {
//LoginBean loginBean = new LoginBean();
loginBean.setUserId(id);
loginBean.setPwd(pwd);
return loginBean;
}
I tried following scenarios to make my #Autowired work:
#Autowired to LoginBean loginBean;
Created getter setter of LoginBean in Controller class and autowired setters;
Created constructor of Controller and autowired, as given in above code;
Below is the error which I am getting
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoRestController': Unsatisfied dependency expressed through constructor argument with index 0 of type [com.ag.digital.demo.bean.LoginBean]: No qualifying bean of type [com.ag.digital.demo.bean.LoginBean] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.ag.digital.demo.bean.LoginBean] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:185) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1143) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1046) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839) ~[spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538) ~[spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) ~[spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:766) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
at org.springframework.boot.SpringApplication.createAndRefreshContext(SpringApplication.java:361) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:307) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1191) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1180) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
at com.ag.digital.demo.boot.DemoApplication.main(DemoApplication.java:14) [classes/:na]
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.ag.digital.demo.bean.LoginBean] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1373) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1119) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:813) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
... 19 common frames omitted
Your DemoApplication class is in the com.ag.digital.demo.boot package and your LoginBean class is in the com.ag.digital.demo.bean package. By default components (classes annotated with #Component) are found if they are in the same package or a sub-package of your main application class DemoApplication. This means that LoginBean isn't being found so dependency injection fails.
There are a couple of ways to solve your problem:
Move LoginBean into com.ag.digital.demo.boot or a sub-package.
Configure the packages that are scanned for components using the scanBasePackages attribute of #SpringBootApplication that should be on DemoApplication.
A few of other things that aren't causing a problem, but are not quite right with the code you've posted:
#Service is a specialisation of #Component so you don't need both on LoginBean
Similarly, #RestController is a specialisation of #Component so you don't need both on DemoRestController
DemoRestController is an unusual place for #EnableAutoConfiguration. That annotation is typically found on your main application class (DemoApplication) either directly or via #SpringBootApplication which is a combination of #ComponentScan, #Configuration, and #EnableAutoConfiguration.
To me it happened in DogController that autowired DogService that autowired DogRepository. Dog class used to have field name but I changed it to coolName, but didn't change methods in DogRepository: Dog findDogByName(String name). I change that method to Dog findDogByCoolName(String name) and now it works.
In my case, this is erroring out during my unit test, apparently, not only do I have to add the new package on the Main class, but also on the Test configuration class where in the ComponentScan annotation specific to the test classes, I just added
com.bpg.csp.cbs.common.util
since this is the new package I added on my project. A snippet of my full test configuration code is below
#Profile("junit")
#Configuration
#ComponentScan(basePackages = {
"com.bpg.services.booking.gds.adapter.impl.config",
"com.bpg.csp.cbs.common.util"
})
public class TestConfiguration
{
}
Also please if your are running a compliance laptop (company laptop) make sure to start mysql by command "mysqld" and logging in it by command "mysql -u [username] -p" and then type your password.
Most of the communication, linking and packet receiving errors are resolved by it.
This is because the all the jdbc and mysql drivers are built on top of the vpn so it is mandatory to connect to it in order to download important jars files and dependencies from the artifactory...
I use the following QuartzConfig configuration class to autowire spring data with quartz, this configuration class works well and fire job once I run project with no errors, but I want to fire jobs manually by the following spring controller but I got #autowire error with spring data
Quartz Job
#Service
#Transactional
public class JobOne implements Job {
#Autowired
TestrecordRepository testrecordRepository;
#Autowired
ScoreRepository scoreRepository;
public void execute(JobExecutionContext context) throws JobExecutionException {
System.out.println("Job one!");
List<Testrecord> records=testrecordRepository.findAll();
for (Testrecord t : records) {
Testrecord testrecord = new Testrecord();
testrecord.setValue_integer(t.getValue_integer());
testrecord.setId(t.getId());
RuleExecutor ruleExecutor = new RuleExecutor();
Score score = ruleExecutor.processRules(testrecord);
scoreRepository.save(score);
}
}
}
configuration class
#Configuration
public class QuartzConfig {
#Autowired
private ApplicationContext applicationContext;
#Bean
public SchedulerFactoryBean quartzSchedulerjobOne() {
SchedulerFactoryBean quartzScheduler = new SchedulerFactoryBean();
quartzScheduler.setOverwriteExistingJobs(true);
AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
jobFactory.setApplicationContext(applicationContext);
quartzScheduler.setJobFactory(jobFactory);
Trigger[] triggers = {
processjobOneTrigger().getObject()
};
quartzScheduler.setTriggers(triggers);
return quartzScheduler;
}
#Bean
public JobDetailFactoryBean processjobOne() {
JobDetailFactoryBean jobDetailFactory = new JobDetailFactoryBean();
jobDetailFactory.setJobClass(JobOne.class);
jobDetailFactory.setDurability(true);
return jobDetailFactory;
}
#Bean
public CronTriggerFactoryBean processjobOneTrigger() {
CronTriggerFactoryBean cronTriggerFactoryBean = new CronTriggerFactoryBean();
cronTriggerFactoryBean.setJobDetail(processjobOne().getObject());
cronTriggerFactoryBean.setCronExpression("0 0/1 * * * ?");
return cronTriggerFactoryBean;
}
}
Spring controller
#RequestMapping(value = "/test", method = RequestMethod.GET)
public void test(HttpServletRequest request) throws Exception {
ApplicationContext context = new AnnotationConfigApplicationContext(
QuartzConfig.class);
Scheduler scheduler = (Scheduler)context.getBean("quartzSchedulerjobOne");
}
eclipse console
[ERROR] org.quartz.core.ErrorLogger - An error occured instantiating job to be executed. job= 'DEFAULT.processJobTwo'
org.quartz.SchedulerException: Job instantiation failed
at org.springframework.scheduling.quartz.AdaptableJobFactory.newJob(AdaptableJobFactory.java:45) ~[spring-context-support-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.quartz.core.JobRunShell.initialize(JobRunShell.java:134) ~[quartz-2.1.5.jar:na]
at org.quartz.core.QuartzSchedulerThread.run(QuartzSchedulerThread.java:387) [quartz-2.1.5.jar:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.innvo.quartz.JobTwo': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.innvo.repository.TestrecordRepository com.innvo.quartz.JobTwo.testrecordRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.innvo.repository.TestrecordRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBean(AbstractAutowireCapableBeanFactory.java:302) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at com.innvo.quartz.AutowiringSpringBeanJobFactory.createJobInstance(AutowiringSpringBeanJobFactory.java:22) ~[classes/:na]
at org.springframework.scheduling.quartz.AdaptableJobFactory.newJob(AdaptableJobFactory.java:41) ~[spring-context-support-4.1.6.RELEASE.jar:4.1.6.RELEASE]
... 2 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.innvo.repository.TestrecordRepository com.innvo.quartz.JobTwo.testrecordRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.innvo.repository.TestrecordRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
... 6 common frames omitted
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.innvo.repository.TestrecordRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1301) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1047) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
... 8 common frames omitted
from the error log that you posted , its clear that its looking for a bean which has not been wrapped by spring.The first bean com.innvo.quartz.JobOne.testrecordRepository where is defined? Are you sure its in the package scan? The bean name quartzSchedulerjobOne that you want to get from the application context , is anywhere defined??
Also why you try to get the Scheduler from the application context , and you dont autowire it to the controller? The scheduler has to be singleton and he will be responsible to start a new job.