So i'm trying to learn spring and i've been reading a lot of tutorials and trying copying some code from a project that I have in a flash drive.
I already set up tomcat and it works find but i'm still having some problems here. The thing is I can normally access a controller's action from my browser without a problem, but when I started adding annotations and ContextLoaderListener it gave me a 404 status all the time. I don't know what I did, but by tweaking some things around, my browser at least tries to reach the controller again. But throws a huge error log which I will share at the end of this post.
These are my dependencies:
- junit 4.12
- spring-webmvc 4.1.6.RELEASE
- spring-context 4.1.6.RELEASE
- spring-web 4.1.6.RELEASE
- spring-beans 4.1.6.RELEASE
- spring-data-jpa 1.8.0.RELEASE
- spring-jdbc 4.1.6.RELEASE
- mysql-connector-java 5.1.35
- jstl 1.2
- javax.servlet-api 3.1.0 (scope provided)
- javax.servlet.jsp-api 3.1.0 (scope provided)
- jackson-databind 2.5.4
- jackson-core 2.5.4
- jackson-core-asl 1.9.13
- jackson-datatype-hibernate4 2.5.4
- hibernate-annotations 3.5.6-Final
- hibernate-commons-annotations 3.2.0.Final
- hibernate-entitymanager 4.3.10.Final
- jsondoc-core 1.1.15
- jsondoc-springmvc 1.1.15
- jsondoc-ui-webjar 1.1.15
- commons-logging 1.2
- commons-logging-api 1.1
- commons-dbcp 1.4
My build plugins are:
- maven-compiler-plugin 3.1 (source and target 1.8)
- maven-war-plugin 2.4
My web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Spring Web MVC Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:WEB-INF/application-context.xml
classpath*:WEB-INF/persistence-context.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
My mvc-dispatcher-servlet
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.ve" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="com.ve.main.HibernateAwareObjectMapper" />
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<bean id="documentationController" class="org.jsondoc.springmvc.controller.JSONDocController">
<constructor-arg name="version" value="1.0"/>
<constructor-arg name="basePath" value="http://localhost:4848/spring2"/>
<constructor-arg name="packages">
<list>
<value>com.ve</value>
</list>
</constructor-arg>
</bean>
My application-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.ve" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Repository" />
<context:include-filter type="annotation" expression="org.springframework.stereotype.Service" />
</context:component-scan>
My persistence-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/my_database" />
<property name="username" value="my_actual_db_user" />
<property name="password" value="my_actual_db_password" />
</bean>
<bean id="persistenceUnitManager" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="defaultDataSource" ref="dataSource" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitManager" ref="persistenceUnitManager" />
<property name="persistenceUnitName" value="persistenceUnit" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<jpa:repositories base-package="com.ve" entity-manager-factory-ref="entityManagerFactory" transaction-manager-ref="transactionManager" />
And just for information i will also quote my classes code and my project structure
StockController
package com.ve.common.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ve.common.service.StockService;
@Controller
@RequestMapping("/stock")
public class StockController {
@Autowired
private StockService stockService;
public StockController(){}
@RequestMapping(value="/list", method = RequestMethod.GET, produces={"application/json","application/xml"})
@ResponseBody
public String findAllStocks(){
return "stocks";
}
}
StockService
package com.ve.common.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ve.common.model.Stock;
import com.ve.common.repo.StockRepository;
@Service
public class StockService {
@Autowired
private StockRepository stockRepository;
StockService(){}
List<Stock> findStock(){
return (List<Stock>) stockRepository.findAll();
}
}
StockRepository
package com.ve.common.repo;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.ve.common.model.Stock;
@Repository
public interface StockRepository extends CrudRepository<Stock, Integer> {
List<Stock> findByStockName(String stockName);
Stock findByStockId(Integer stockId);
}
My model is a basic Entity class that implements Serializable (created by JPA tools). Now this is my project structure, I'm sorry I couldn't make the image smaller (i'm in a ruch at the moment).
And here is a quote of that huge error i get in my browser when i access "http://localhost:4848/spring2/api/welcome/hi" or "http://localhost:4848/spring2/api/stock/list"
HTTP Status 500 - Servlet.init() for servlet mvc-dispatcher threw exception
type Exception report
message Servlet.init() for servlet mvc-dispatcher threw exception
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Servlet.init() for servlet mvc-dispatcher threw exception org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99) org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407) org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004) org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) java.lang.Thread.run(Thread.java:745)
root cause
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'stockController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ve.common.service.StockService com.ve.common.controller.StockController.stockService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.ve.common.service.StockService] 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)} org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755) org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757) org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480) org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677) org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548) org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489) org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136) javax.servlet.GenericServlet.init(GenericServlet.java:160) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99) org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407) org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004) org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) java.lang.Thread.run(Thread.java:745)
root cause
org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ve.common.service.StockService com.ve.common.controller.StockController.stockService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.ve.common.service.StockService] 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)} org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561) org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755) org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757) org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480) org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677) org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548) org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489) org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136) javax.servlet.GenericServlet.init(GenericServlet.java:160) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99) org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407) org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004) org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) java.lang.Thread.run(Thread.java:745)
root cause
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.ve.common.service.StockService] 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)} org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1301) org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1047) org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942) org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533) org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755) org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757) org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480) org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677) org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548) org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489) org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136) javax.servlet.GenericServlet.init(GenericServlet.java:160) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99) org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407) org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004) org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) java.lang.Thread.run(Thread.java:745)
I apologize for the excessive code blocking and blockquoting, but I think the more information I provide, the better help I can get. And I thank in advance whoever can give me a hand.
When @Autowired doesn't work. There are several reasons @Autowired might not work. When a new instance is created not by Spring but by for example manually calling a constructor, the instance of the class will not be registered in the Spring context and thus not available for dependency injection.
There could be numerous reasons why Spring could not able to create a bean with name X, but clue always lies on the detailed stack trace. This error always has some underlying cause e.g. a ClassNotFoundException or a NoClassDefFoundError, which potentially signal a missing JAR file in the classpath.
Spring @Autowired annotation is used for automatic dependency injection. Spring framework is built on dependency injection and we inject the class dependencies through spring bean configuration file.
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.ve.common.service.StockService]
The error itself says that SpringContainer doesn't find the bean with name StockService
. So either you create bean in applicationContext.xml
file or declare bean with the @Bean
annotation.
@Autowired : This annotation allows you to not explicitly declaring your bean in applicationContext.xml
. But you have to create bean of class you want to autowire using @Bean
annotation & add <context:conponent-scan>
in XML
to know the bean is being created using @Bean
annotation.
Declaring Bean : To declare bean annotate the method with @Bean
annotation just like
@Configuration
public class AppConfig {
@Bean
public StockService stockService() {
return new StockServiceImpl();
}
}
This is equivalent to declaring bean in the applicationContext.xml
<beans>
<bean name="stockService" class="com.ve.common.service.StockServiceImpl"/>
</beans>
OR
If you want to use @Autowired
annotation in a bean class then must first have to enable annotation in spring using below configuration:
<context:annotation-config />
or
<bean class ="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
For More Info :
Hope this helps you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With