Rad*_*ski 76 java spring annotations spring-mvc autowired
我通过使用Spring和Hibernate为服务创建实体,服务和JUnit测试来启动我的项目.所有这一切都很棒.然后我添加了spring-mvc来使用许多不同的分步教程来创建这个Web应用程序,但是当我尝试使用@Autowired注释创建Controller时,我在部署期间遇到来自Glassfish的错误.我想由于某些原因Spring没有看到我的服务,但经过多次尝试后我仍然无法处理它.
服务测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/beans.xml"})
Run Code Online (Sandbox Code Playgroud)
和
@Autowired
MailManager mailManager;
Run Code Online (Sandbox Code Playgroud)
工作正常.
没有@Autowired的控制器,我可以毫无困难地在Web浏览器中打开我的项目.
/src/main/resources/beans.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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_2_0.xsd">
<context:property-placeholder location="jdbc.properties" />
<context:component-scan base-package="pl.com.radzikowski.webmail">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<!--<context:component-scan base-package="pl.com.radzikowski.webmail.service" />-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- Persistance Unit Manager for persistance options managing -->
<bean id="persistenceUnitManager" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="defaultDataSource" ref="dataSource"/>
</bean>
<!-- Entity Manager Factory for creating/updating DB schema based on persistence files and entity classes -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitManager" ref="persistenceUnitManager"/>
<property name="persistenceUnitName" value="WebMailPU"/>
</bean>
<!-- Hibernate Session Factory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--<property name="schemaUpdate" value="true" />-->
<property name="packagesToScan" value="pl.com.radzikowski.webmail.domain" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
</props>
</property>
</bean>
<!-- Hibernate Transaction Manager -->
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- Activates annotation based transaction management -->
<tx:annotation-driven transaction-manager="txManager"/>
</beans>
Run Code Online (Sandbox Code Playgroud)
/webapp/WEB-INF/web.xml
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" id="WebApp_ID" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring Web MVC Application</display-name>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
Run Code Online (Sandbox Code Playgroud)
/webapp/WEB-INF/mvc-dispatcher-servlet.xml
<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-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="pl.com.radzikowski.webmail" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
Run Code Online (Sandbox Code Playgroud)
pl.com.radzikowski.webmail.service.AbstractManager
package pl.com.radzikowski.webmail.service;
import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
/**
* Master Manager class providing basic fields for services.
* @author Maciej Radzikowski <maciej@radzikowski.com.pl>
*/
public class AbstractManager {
@Autowired
protected SessionFactory sessionFactory;
protected final Logger logger = Logger.getLogger(this.getClass());
}
Run Code Online (Sandbox Code Playgroud)
pl.com.radzikowski.webmail.service.MailManager
package pl.com.radzikowski.webmail.service;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
@Component
@Transactional
public class MailManager extends AbstractManager {
// some methods...
}
Run Code Online (Sandbox Code Playgroud)
pl.com.radzikowski.webmail.HomeController
package pl.com.radzikowski.webmail.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import pl.com.radzikowski.webmail.service.MailManager;
@Controller
@RequestMapping("/")
public class HomeController {
@Autowired
public MailManager mailManager;
@RequestMapping(value = "/", method = RequestMethod.GET)
public String homepage(ModelMap model) {
return "homepage";
}
}
Run Code Online (Sandbox Code Playgroud)
错误:
SEVERE: Exception while loading the app
SEVERE: Undeployment failed for context /WebMail
SEVERE: Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'homeController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public pl.com.radzikowski.webmail.service.MailManager pl.com.radzikowski.webmail.controller.HomeController.mailManager; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [pl.com.radzikowski.webmail.service.MailManager] 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)}
Run Code Online (Sandbox Code Playgroud)
很抱歉有很多代码,但我不知道是什么原因造成了这个错误.
添加
我创建了界面:
@Component
public interface IMailManager {
Run Code Online (Sandbox Code Playgroud)
添加工具:
@Component
@Transactional
public class MailManager extends AbstractManager implements IMailManager {
Run Code Online (Sandbox Code Playgroud)
并更改了自动装配:
@Autowired
public IMailManager mailManager;
Run Code Online (Sandbox Code Playgroud)
但它仍然会引发错误(当我尝试使用@Qualifier时)
..不能autowire字段:public pl.com.radzikowski.webmail.service.IMailManager pl.com.radzikowski.webmail.controller.HomeController.mailManager ...
我也试过了@Component和@Transactional的不同组合.
我不应该以某种方式在web.xml中包含beans.xml吗?
Pat*_*son 73
您应该自动连接接口AbstractManager而不是类MailManager.如果您有不同的实现,AbstractManager您可以编写@Component("mailService")然后@Autowired @Qualifier("mailService")组合以自动装配特定的类.
这是因为Spring根据接口创建并使用代理对象.
moo*_*eds 24
我发生这种情况是因为我的测试与我的组件不在同一个包中.(我已经重命名了我的组件包,但不是我的测试包.)而且我@ComponentScan在我的测试@Configuration类中使用,所以我的测试没有找到他们所依赖的组件.
所以,仔细检查一下,如果你收到这个错误.
问题是在服务器启动期间,应用程序上下文和Web应用程序上下文都在WebApplicationContext中注册.运行测试时,必须明确指出要加载的上下文.
试试这个:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/beans.xml", "/mvc-dispatcher-servlet.xml"})
Run Code Online (Sandbox Code Playgroud)
我在从我的 jar 文件之一自动连接类时遇到了同样的问题。我通过使用 @Lazy 注释解决了该问题:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
@Autowired
@Lazy
private IGalaxyCommand iGalaxyCommand;
Run Code Online (Sandbox Code Playgroud)
这可能会帮助您:
我的项目中也有同样的例外。经过搜索后,我发现我缺少对@Service正在实现我想要的接口的类的注释@Autowired。
在您的代码中,您可以将@Service注释添加到MailManager类中。
@Transactional
@Service
public class MailManager extends AbstractManager implements IMailManager {
Run Code Online (Sandbox Code Playgroud)
小智 7
尽管我启用了包特定扫描,但在我的 Spring Boot 应用程序中遇到了同样的问题
@SpringBootApplication(scanBasePackages={"com.*"})
Run Code Online (Sandbox Code Playgroud)
但是,通过在我的应用程序类中提供,问题得到了解决@ComponentScan({"com.*"})。
花了很多时间在这上面!我的错!后来发现我声明了注释的类Service或Component类型为abstract的类.已在Springframework上启用调试日志但未收到任何提示.请检查类是否为抽象类型.如果那时,应用了基本规则,则无法实例化抽象类.
| 归档时间: |
|
| 查看次数: |
480217 次 |
| 最近记录: |