我通过使用 Spring 和 Hibernate 为服务创建实体、服务和 JUnit 测试来开始我的项目。所有这一切都很好。然后我添加了 spring-mvc 以使用许多不同的分步教程制作这个 Web 应用程序,但是当我尝试使用 @Autowired
注释制作控制器时,我在部署期间从 Glassfish 收到错误。我猜出于某种原因,Spring 看不到我的服务,但经过多次尝试,我仍然无法处理它。
测试服务
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/beans.xml"})
和
@Autowired
MailManager mailManager;
工作正常。
也没有 @Autowired
的控制器,我可以在网络浏览器中毫无问题地打开我的项目。
/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>
/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>
/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>
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());
}
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...
}
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";
}
}
错误:
严重:加载应用程序时出现异常严重:上下文/WebMail 取消部署失败严重:加载应用程序时出现异常:java.lang.IllegalStateException:ContainerBase.addChild:开始:org.apache.catalina.LifecycleException:org.springframework.beans.factory .BeanCreationException:创建名为“homeController”的bean时出错:注入自动装配的依赖项失败;嵌套异常是 org.springframework.beans.factory.BeanCreationException:无法自动装配字段:public pl.com.radzikowski.webmail.service.MailManager pl.com.radzikowski.webmail.controller.HomeController.mailManager;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [pl.com.radzikowski.webmail.service.MailManager] found for dependency: 预计至少有 1 个 bean 有资格作为此依赖项的自动装配候选者。依赖注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)}
很抱歉有很多代码,但我不知道是什么导致该错误了。
添加
我已经创建了界面:
@Component
public interface IMailManager {
添加的工具:
@Component
@Transactional
public class MailManager extends AbstractManager implements IMailManager {
并更改了自动连线:
@Autowired
public IMailManager mailManager;
但它仍然会引发错误(当我尝试使用 @Qualifier
时也是如此)
..无法自动装配字段:public pl.com.radzikowski.webmail.service.IMailManager pl.com.radzikowski.webmail.controller.HomeController.mailManager...
我也尝试了 @Component
和 @Transactional
的不同组合。
我不应该以某种方式在 web.xml 中包含 beans.xml 吗?
MailManagerInterface
和 IMailManager
之一? :)
IMailManager
。
<import resource="classpath:/beans.xml"/>
添加到 mvc-dispatcher-servlet.xml
您应该自动装配接口 AbstractManager
而不是类 MailManager
。如果您有不同的 AbstractManager
实现,您可以编写 @Component("mailService")
然后 @Autowired @Qualifier("mailService")
组合来自动装配特定类。
这是因为 Spring 基于接口创建和使用代理对象。
我发生这种情况是因为我的测试与我的组件不在同一个包中。 (我重命名了我的组件包,但没有重命名我的测试包。)而且我在我的测试 @Configuration
类中使用了 @ComponentScan
,所以我的测试没有找到它们所依赖的组件。
因此,请仔细检查您是否收到此错误。
src/test
中使用来自 src/main
的 @Configuration
类?
问题是应用程序上下文和 Web 应用程序上下文都在服务器启动期间在 WebApplicationContext 中注册。当您运行测试时,您必须明确告知要加载哪些上下文。
尝试这个:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/beans.xml", "/mvc-dispatcher-servlet.xml"})
@SpringBootApplication(scanBasePackages = { "com.package.one", "com.package.two" })
从我的一个 jar 文件自动连接类时,我遇到了同样的问题。我通过使用 @Lazy 注释解决了这个问题:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
@Autowired
@Lazy
private IGalaxyCommand iGalaxyCommand;
@Lazy
,或者启用 { 2} ?!?我猜是时间/比赛条件问题? (添加日志会使事情变慢,足以延迟解决问题的事情?)太奇怪了
这可能会帮助您:
我的项目中有同样的例外。在搜索之后,我发现我在实现我想要的接口的类中缺少 @Service
注释 @Autowired
。
在您的代码中,您可以将 @Service
注释添加到 MailManager
类。
@Transactional
@Service
public class MailManager extends AbstractManager implements IMailManager {
@Service
注释包含 @Component
。两者兼有是多余的。
我花了很多时间在这上面!我的错!后来发现我声明注解Service
或Component
的类是abstract类型。已在 Springframework 上启用调试日志,但未收到任何提示。请检查类是否为抽象类型。如果这样,应用的基本规则不能实例化抽象类。
正如 Max 建议的那样,正确的方法应该是自动装配 AbstractManager,但这也应该可以正常工作。
@Autowired
@Qualifier(value="mailService")
public MailManager mailManager;
和
@Component("mailService")
@Transactional
public class MailManager extends AbstractManager {
}
您可以尝试使用 @Component
仅注释您的具体实现吗?也许以下 answer 可以提供帮助。这是一个类似的问题。我通常将Spring注解放在实现类中。
https://stackoverflow.com/a/10322456/2619091
我最近遇到了这个问题,事实证明,我在我的服务类中导入了错误的注释。 Netbeans 有一个隐藏导入语句的选项,这就是为什么我有一段时间没有看到它的原因。
我使用 @org.jvnet.hk2.annotations.Service
而不是 @org.springframework.stereotype.Service
。
即使我启用了特定于包的扫描,但在我的 Spring Boot 应用程序中也遇到了同样的问题
@SpringBootApplication(scanBasePackages={"com.*"})
但是,通过在我的 Application 类中提供 @ComponentScan({"com.*"})
解决了这个问题。
对我有用的解决方案是将所有相关类添加到测试类的 @ContextConfiguration
注释中。
要测试的类 MyClass.java
有两个自动装配组件:AutowireA
和 AutowireB
。这是我的修复。
@ContextConfiguration(classes = {MyClass.class, AutowireA.class, AutowireB.class})
public class MyClassTest {
...
}
上下文中可能不存在 BeanB 的原因之一
异常的另一个原因是存在两个 bean
或者未定义的上下文 bean 中的定义是由 Spring 上下文中的名称请求的
查看更多此网址:
http://www.baeldung.com/spring-nosuchbeandefinitionexception
<context:component-scan base-package="com.*" />
同样的问题出现了,我通过保持注释完整并在调度程序 servlet :: 将基本包扫描保持为 com.*.
来解决它,这对我有用。
您可以模拟 bean,而不是 @Autowire MailManager mailManager,如下所示:
import org.springframework.boot.test.mock.mockito.MockBean;
::
::
@MockBean MailManager mailManager;
此外,您可以在 @SpringBootConfiguration
类中单独配置 @MockBean MailManager mailManager;
并初始化如下:
@Autowire MailManager mailManager
我的猜测是这里
<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>
use-default-filters="false"
首先禁用所有注释,然后仅启用 @Controller
注释。因此,您的 @Component
注释未启用。
如果您正在测试您的控制器。不要忘记在您的测试类上使用@WebAppConfiguration。
我发生这种情况是因为我向我的服务类添加了一个自动装配的依赖项,但忘记将它添加到我的服务单元测试中的注入模拟中。
当问题实际上在单元测试中时,单元测试异常似乎报告了服务类中的问题。回想起来,错误消息告诉我到底是什么问题。
我遇到了同样的问题,使用以下步骤解决了问题:
检查您正在自动连接的类/接口对于接口业务逻辑,我们应该在扩展接口方法时使用@service。对于作为数据库处理类的 Dao,我们应该使用 @Repository。
→ 我们可以有效地使用@Service
、@Repository
和@Component
注解,并很快解决这个问题。
如果您正在测试 DAO 层,则必须使用 @Autowire
注释,如下所示:
@Autowired
private FournisseurDao fournisseurDao;
不要在构造函数中注入存储库元素
我在带有 No qualifying bean of type
的多模块项目中重现了类似的问题,例如:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.stockclient.repository.StockPriceRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
在我的特定用例中,此错误的原因是缺少注释 @EnableJpaRepositories
。
澄清:需要添加此注释以启用对需要了解 JPA
存储库路径的 Spring Data JPA
的自动配置支持。默认情况下,它将仅扫描主应用程序包及其子包以检测 JPA
存储库。
例如,有关更多详细信息,您可以参考此 article。
@Autowired AbstractManager[] abstractManagers
之类的操作。MailManager
?@Service
类。两者都是@Autowired
在另一个类。最初,当我使用特定的类类型时,它引起了与原始帖子相同的问题。按照这个答案,我改为使用具有不同@Qualifier("myServiceA")
和@Qualifier("myServiceB")
的接口类型,问题得到解决。谢谢!