복붙노트

[SPRING] @Autowired (required = false) 생성자에서 NoSuchBeanDefinitionException을 제공함

SPRING

@Autowired (required = false) 생성자에서 NoSuchBeanDefinitionException을 제공함

Spring 애플리케이션에서 @Autowired (required = false)를 생성자에 사용했습니다. 즉, autowired 될 bean이 xml 파일에서 사용 가능하지 않으면 (required = false) 언급되었으므로 NoSuchBeanDefinitionException을 발생시켜야합니다. 하지만 UnsatisfiedDependencyException, NoSuchBeanDefinitionException 예외가 나타납니다.

---- 텍스트 편집기

public class TextEditor {

    private SpellChecker x;
    private String name;    

    @Autowired(required=false)
    public TextEditor(SpellChecker x) {
        System.out.println("Inside TextEditor constructor." );
        this.x = x;
    }


    public SpellChecker getY() {
        return x;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void spellCheck() {
        x.checkSpelling();
    }
}

---- 맞춤법 검사기

public class SpellChecker {
    public SpellChecker() {
        System.out.println("Inside SpellChecker constructor.");
    }

    public void checkSpelling() {
        System.out.println("Inside checkSpelling.");
    }
}

---- Beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:aks="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    aks: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:annotation-config />

    <bean id="textEditor" class="com.tutorialspoint.TextEditor">
        <!-- <property name="x" ref="a" /> -->
        <property name="name" value="Generic Text Editor" />
    </bean>

    <!-- <bean id="a" class="com.tutorialspoint.SpellChecker" /> -->

</beans>

---- MainApp
public class MainApp {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "Beans.xml");//Beans.xml, Beans1.xml
        TextEditor te = (TextEditor) context.getBean("textEditor");
        //te.spellCheck();
        System.out.println(te.getY());
    }
}

--- 콘솔 (실제 결과)

Apr 24, 2014 4:30:00 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@15eb0a9: startup date [Thu Apr 24 16:30:00 IST 2014]; root of context hierarchy
Apr 24, 2014 4:30:00 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [Beans.xml]
Apr 24, 2014 4:30:00 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@2d9c06: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,textEditor]; root of factory hierarchy
Apr 24, 2014 4:30:00 PM org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@2d9c06: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,textEditor]; root of factory hierarchy
Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'textEditor' defined in class path resource [Beans.xml]: Unsatisfied dependency expressed through constructor argument with index 0 of type [com.tutorialspoint.SpellChecker]: : No matching bean of type [com.tutorialspoint.SpellChecker] 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 matching bean of type [com.tutorialspoint.SpellChecker] 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:730)
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:196)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1002)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:906)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:484)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:455)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:192)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at com.tutorialspoint.MainApp.main(MainApp.java:8)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.tutorialspoint.SpellChecker] 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:924)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:793)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:707)
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:795)
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:723)
    ... 15 more

--- 예상 결과 @Autowire (required = false)가 생성자에 대해 언급되었으므로 예외없이 프로그램을 실행해야합니다. 빈이 발견되지 않더라도 (required = false) 예외가 발생하지 않아야합니다.

해결법

  1. ==============================

    1.이 예외는 required = false가 null을 주입한다는 것을 의미하지 않기 때문에 발생합니다. 생성자에 적용될 때 Spring은 인스턴스 생성에 가장 적합한 생성자를 결정하려고 시도합니다. 이 경우에는 SpellChecker가 필요하지만 해당 유형의 객체는없는 생성자가 하나만 있습니다.

    이 예외는 required = false가 null을 주입한다는 것을 의미하지 않기 때문에 발생합니다. 생성자에 적용될 때 Spring은 인스턴스 생성에 가장 적합한 생성자를 결정하려고 시도합니다. 이 경우에는 SpellChecker가 필요하지만 해당 유형의 객체는없는 생성자가 하나만 있습니다.

    Spring 문서 (http://docs.spring.io/spring/docs/4.0.x/javadoc-api/org/springframework/beans/factory/annotation/Autowired.html)에서 참조한 것처럼

    어쨌든 기본 생성자 (private 일 수있다)를 추가하면 Spring이 @Autowired 매직을 할 수 없을 때 사용할 수있다. TextEditor 클래스에서 다음을 추가 할 수 있습니다.

    @Deprecated
    private TextEditor() {
        // You could leave x = null or create a default value for that field 
        // if you have one (eg. x = new DefaultSpellChecker();)
    }
    

    @Deprecated는 아무도 사용하지 않는 개인 생성자가 있음을 컴파일러가 경고하지 않도록하기 위해 사용됩니다.

  2. ==============================

    2.나는 비슷한 문제가 있었다. 사실, 여러 생성자를 가질 수 있습니다.

    나는 비슷한 문제가 있었다. 사실, 여러 생성자를 가질 수 있습니다.

    @Autowired(required = false)
    

    그러나 @Autowired 주석에는 적어도 하나의 인수가 필요하기 때문에이 주석을 기본적으로 (인수없이) 생성자에 추가 할 수 없다는 점에 유의하십시오.

  3. from https://stackoverflow.com/questions/23267440/autowiredrequired-false-on-constructor-giving-nosuchbeandefinitionexception by cc-by-sa and MIT license