source

@Autowired - 종속성에 적합한 빈 유형을 찾을 수 없습니다.

bestscript 2023. 1. 6. 19:55

@Autowired - 종속성에 적합한 빈 유형을 찾을 수 없습니다.

Spring과 Hibernate를 사용한 서비스의 엔티티, 서비스 및 JUnit 테스트를 작성하는 것으로 프로젝트를 시작했습니다.이 모든 것이 잘 작동한다. 이 웹 여러 튜토리얼을 , '스프링-mvc'를 사용하여 컨트롤러를 할 때 입니다.다양한 단계별 튜토리얼을 사용하고 있습니다만, 컨트롤러는@Autowired유리 물고기아무래도 스프링이 내 서비스를 못 보는 것 같아. 하지만 여러 번 시도해 봤지만 난 여전히 감당할 수 없어.

서비스 테스트

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/beans.xml"})

그리고.

@Autowired
MailManager mailManager;

올바르게 동작합니다.

" " 가 없는 @Autowired웹 브라우저에서도 문제없이 프로젝트를 열 수 있습니다.

/src/main/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.웹 메일.서비스.Abstract Manager

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.웹 메일.서비스.메일 매니저

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.웹 메일.홈 컨트롤러

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에 취소 : "/ WebMail" 입니다.
java.java.InlawalStateException:ContainerBase.addChild: org.apache.catalina.라이프 사이클 예외: org.spring 프레임워크."." 예외: 'homeController 동안 했습니다.홈 컨트롤러'를 선택합니다.자동 배선 종속성을 주입하지 못했습니다. org.springframework."." 예외pl.radzikowskipublic pl.com.radzikowski 필드할 수 없습니다.serviceservicepl메일 매니저 pl.com.radzikowski.webmail.controller.HomeController.mailManager.nasted org.springframework.콩no 。 No Such Bean Definition ( Such Bean Definition)이러한 Bean Definition ( : [ pl. radzikowski ].[ pl.com . radzikowski ] 타 [ [ 、 serviceservice대해 ".. 이종속성에 합니다.종속성에 대한 MailManager]를 찾았습니다. 이 종속성에 대한 자동 배선 후보로 적합한 빈이 하나 이상 필요합니다.{@framework..factory.informationdisplayation.disposition.disposition공배 。 ( true )}이(가)= true(참)}

코드가 많아서 죄송합니다만, 그 에러의 원인이 무엇인지 더 이상 모르겠습니다.

추가된

인터페이스를 만들었습니다.

@Component
public interface IMailManager {

추가된 구현:

@Component
@Transactional
public class MailManager extends AbstractManager implements IMailManager {

변경 후 자동 전원:

@Autowired
public IMailManager mailManager;

에러가 제가 @Qualifier)

..public pl.com.radzikowski 필드를 자동 배선할 수 없습니다.웹 메일.서비스.IMail Manager pl.com.radzikowski.webmail.controller.HomeController.mailManager...

여러 @Component ★★★★★★★★★★★★★★★★★」@Transactional

web.xml에 beans.xml을 포함시켜야 하지 않을까요?

「 interface」는, 「Autowire interface」로 할 가 있습니다.AbstractManager 대신MailManagerAbstractManager 쓸 수 요.@Component("mailService") 다음에 또 한 번.@Autowired @Qualifier("mailService")특정 클래스를 자동 배선하는 조합입니다.

이는 Spring이 인터페이스를 기반으로 프록시 개체를 만들고 사용하기 때문입니다.

컴포넌트패키지는 되지 않았습니다.(컴포넌트 패키지의 이름되지 않았습니다.) 저는 리 and and리 and 、 and 。@ComponentScan @Configuration그래서 제 테스트는 그들이 의지하는 컴포넌트를 찾지 못했습니다.

이 에러가 발생했을 경우는, 재차 확인해 주세요.

중요한 것은 애플리케이션콘텍스트와 웹 어플리케이션콘텍스트가 모두 서버 부팅 시 Web ApplicationContext에 등록된다는 것입니다.테스트를 실행할 때는 로드하는 컨텍스트를 명시적으로 지정해야 합니다.

이것을 시험해 보세요.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/beans.xml", "/mvc-dispatcher-servlet.xml"})

제 jar 파일 중 하나에서 클래스를 자동 배선하는 동안 같은 문제에 직면했습니다.@Lazy 주석을 사용하여 문제를 해결했습니다.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

    @Autowired
    @Lazy
    private IGalaxyCommand iGalaxyCommand;

다음과 같은 이점이 있습니다.

제 프로젝트에서도 같은 예외가 있습니다.해 보니, 「이러다」, 「이러다」가 을 알 수 .@Service가 를 실장하고 있는 에 대한 @Autowired.

에 '코드로'를 추가할 수 .@Service을 붙일 수 있습니다.MailManager를 누릅니다

@Transactional
@Service
public class MailManager extends AbstractManager implements IMailManager {

이것과 함께 많은 시간을 보냈죠!는 나중에 알았다.Service ★★★★★★★★★★★★★★★★★」Component이치노스프링프레임워크수업이 추상형인지 확인해 주세요.기본 규칙이 적용되는 경우 추상 클래스를 인스턴스화할 수 없습니다.

패키지 고유의 스캔이 유효하게 되어 있는데도, 스프링 부트 애플리케이션에서도 같은 문제가 발생했습니다.

@SpringBootApplication(scanBasePackages={"com.*"})

이 는 '이렇게 하다'를 이 되었습니다.@ComponentScan({"com.*"})내 어플리케이션 수업에서.

Max의 제안대로 Abstract Manager를 자동 배선하는 것이 올바른 방법이지만, 이것도 정상적으로 동작합니다.

@Autowired
@Qualifier(value="mailService")
public MailManager mailManager;

그리고.

@Component("mailService")
@Transactional
public class MailManager extends AbstractManager {
}

만 ''으로 표기해 볼 수 ?@Component다음 답변이 도움이 될 수도 있습니다.그것은 비슷한 문제이다.저는 보통 스프링 주석을 구현 클래스에 넣습니다.

https://stackoverflow.com/a/10322456/2619091

최근에 이 정보를 확인했는데 서비스 클래스에 잘못된 주석을 가져왔습니다.Netbeans에는 Import 스테이트먼트를 숨길 수 있는 옵션이 있기 때문에 한동안 볼 수 없었습니다.

가 쓴 적이 있어요.@org.jvnet.hk2.annotations.Service@org.springframework.stereotype.Service.

나에게 효과가 있었던 솔루션은 모든 관련 클래스를 추가해 주는 것이었다.@ContextConfiguration테스트 클래스에 대한 주석입니다.

하는 클래스, ★★★★★★★★★★★★★★★★★★★★★★★★★★」MyClass.java에는 2개의 컴포넌트, 즉 2개의 컴포넌트가 AutowireA ★★★★★★★★★★★★★★★★★」AutowireB여기 제 해결책이 있습니다.

@ContextConfiguration(classes = {MyClass.class, AutowireA.class, AutowireB.class})
public class MyClassTest {
...
}
  • 컨텍스트에 BeanB가 존재하지 않는 이유 중 하나
  • 예외의 또 다른 원인은 두 개의 콩이 있다는 것이다.
  • 또는 정의되지 않은 컨텍스트 bean의 정의는 Spring 컨텍스트에서 이름으로 요청됩니다.

자세한 것은, 다음의 URL 을 참조해 주세요.

http://www.baeldung.com/spring-nosuchbeandefinitionexception

 <context:component-scan base-package="com.*" />

같은 문제가 도착했습니다.주석을 그대로 두고 디스패처 서블릿 :: 기본 패키지 스캔을 그대로 유지함으로써 해결했습니다.com.*.이건 나한테 효과가 있었어요.

@Autowire MailManager mailManager 대신 다음과 같이 빈을 조롱할 수 있습니다.

import org.springframework.boot.test.mock.mockito.MockBean;

::
::

@MockBean MailManager mailManager;

also, 음, 음, 다, 다, 다, 다, 습, 습, 습, also, also, also, also, also을 설정할 수 있습니다.@MockBean MailManager mailManager;@SpringBootConfiguration초기화하다

@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을 사용하는 것을 잊지 마십시오.

서비스 클래스에 자동 배선 종속성을 추가했는데 서비스 유닛 테스트에서 삽입된 모크에 추가하는 것을 잊어버렸기 때문에 이 문제가 발생했습니다.

유닛 테스트 예외는 실제로 유닛테스트에 문제가 있을 때 서비스 클래스의 문제를 보고하는 것으로 보입니다.돌이켜보면, 에러 메세지는 문제가 무엇인지 정확히 말해줍니다.

같은 문제에 직면했습니다.이 문제는, 다음의 순서로 해결되었습니다.

  1. 자동 배선하고 있는 클래스/인터페이스를 확인합니다.
  2. 에는 " "를 사용해야 .@service인터페이스 메서드를 확장합니다.
  3. 의 경우 Dao를 해야 합니다.@Repository.

→할 수 있다@Service,@Repository ★★★★★★★★★★★★★★★★★」@Component효과적으로 주석을 달아 이 문제를 매우 빠르게 해결합니다.

DAO를 .@Autowire★★★★

@Autowired
private FournisseurDao fournisseurDao;

생성자에 리포지토리 요소 주입 안 함

project 와 와 같은 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제 특정 사용 예에서는요.

명확히 하기 위해: 이 주석은 자동 구성 지원을 활성화하기 위해 추가되어야 합니다.Spring Data JPA을 알 가 있다JPA메인 검출합니다.JPA장소입입니니다

상세한 것에 대하여는, 예를 들면 이 기사를 참조해 주세요.

두.@Bean@Configuration를 클릭합니다하나의 선언이 다른 선언보다 우선한 것으로 보인다.

언급URL : https://stackoverflow.com/questions/20333147/autowired-no-qualifying-bean-of-type-found-for-dependency