8

Stworzyłem 2 proste klasy. Konstruktor jednej klasy opatrzony jest adnotacją @Autowired. Akceptuje obiekt innej klasy. Ale ten kod nie działa.Wstrzyknięcie konstruktora przy użyciu adnotacji wiosennej @Autowired nie działa

Ćwiczenia: - 1) SimpleBean.java

@Configuration 
public class SimpleBean { 
    InnerBean prop1; 

    public InnerBean getProp1() { 
    return prop1; 
    } 

    public void setProp1(InnerBean prop1) { 
    System.out.println("inside setProp1 input inner's property is " 
     + prop1.getSimpleProp1()); 
    this.prop1 = prop1; 
    } 

    @Autowired(required=true) 
    public SimpleBean(InnerBean prop1) { 
    super(); 
    System.out.println("inside SimpleBean constructor inner's property is " 
     + prop1.getSimpleProp1()); 
    this.prop1 = prop1; 
    } 
} 

2) Inner.java

@Configuration 
public class InnerBean { 
    String simpleProp1; 

    public String getSimpleProp1() { 
    return simpleProp1; 
    } 

    public void setSimpleProp1(String simpleProp1) { 
    this.simpleProp1 = simpleProp1; 
    } 

} 

Kiedy próbuję załadować ApplicationConext

ApplicationContext acnxt = new AnnotationConfigApplicationContext("com.domain"); 

daje następujący błąd: -

Exception in thread "main" org.springframework.beans.factory.BeanCreationException:   Error creating bean with name 'simpleBean' defined in file [C:\Users\owner\Documents\Java Project\MyWorkSpace\springMVCSecond\WebContent\WEB-INF\classes\com\domain\SimpleBean.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.domain.SimpleBean$$EnhancerByCGLIB$$4bc418be]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.domain.SimpleBean$$EnhancerByCGLIB$$4bc418be.<init>() 
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:965) 
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:911) 
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485) 
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) 
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.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:75) 
at com.test.SpringAnnotationTest.main(SpringAnnotationTest.java:12) 
Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.domain.SimpleBean$$EnhancerByCGLIB$$4bc418be]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.domain.SimpleBean$$EnhancerByCGLIB$$4bc418be.<init>() 
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:70) 
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:958) 
... 12 more 
Caused by: java.lang.NoSuchMethodException: com.domain.SimpleBean$$EnhancerByCGLIB$$4bc418be.<init>() 
at java.lang.Class.getConstructor0(Unknown Source) 
at java.lang.Class.getDeclaredConstructor(Unknown Source) 
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:65) 
... 13 more 

Jeśli wprowadzę konstruktor no-arg w klasie SimpleBean. Nie daje błędu. Ale to nie daje mi wstępnie odgórnego obiektu SimpleBean (jak w konfiguracji XML przy użyciu < constructor-arg>). A więc przy korzystaniu z adnotacji należy obowiązkowo mieć konstruktor no-arg? Jakie jest właściwe wyjście?

+0

Czy próbujesz wywołać jak 'AnnotationConfigApplicationContext (" com.domain ")' Pakiet? Proszę podać swój kompletny kod. –

+0

@RaviParekh tak, te klasy są w pakiecie com.domain. I próbuję wywołać ApplicationContext acnxt = new AnnotationConfigApplicationContext ("com.domain"); Było już wspomniane. –

Odpowiedz

20

Z javadoc z @Configuration:

Configuration is meta-annotated as a {@link Component}, therefore Configuration 
classes are candidates for component-scanning and may also take advantage of 
{@link Autowired} at the field and method but not at the constructor level. 

Więc trzeba znaleźć jakiś inny sposób to zrobić, niestety.

6

Wydaje mi się, że miksujesz adnotację @Configuration i @Component. Jak na spring docs, @Configuration służy do tworzenia ziarna za pomocą kodu Java (żadnych metod adnotacją z @Bean stworzenia fasoli, podczas zajęć opatrzone @Component są tworzone automatycznie ..

Mam nadzieję, że ten ilustruje następujący:

InnerBean .java:

// this bean will be created by Config 
public class InnerBean { 
    String simpleProp1; 

    public String getSimpleProp1() { 
    return simpleProp1; 
    } 

    public void setSimpleProp1(String simpleProp1) { 
    this.simpleProp1 = simpleProp1; 
    } 
} 

SimpleBean.java:

// This bean will be created because of the @Component annotation, 
// using the constructor with the inner bean autowired in 
@Component 
public class SimpleBean { 
    InnerBean prop1; 

    public InnerBean getProp1() { 
    return prop1; 
    } 

    @Autowired(required = true) 
    public SimpleBean(InnerBean prop1) { 
    this.prop1 = prop1; 
    } 
} 

OuterBean.java

// this bean will be created by Config and have the SimpleBean autowired. 
public class OuterBean { 
    SimpleBean simpleBean; 

    @Autowired 
    public void setSimpleBean(SimpleBean simpleBean) { 
    this.simpleBean = simpleBean; 
    } 

    public SimpleBean getSimpleBean() { 
    return simpleBean; 
    } 
} 

Config.java

// this class will create other beans 
@Configuration 
public class Config { 
    @Bean 
    public OuterBean outerBean() { 
    return new OuterBean(); 
    } 

    @Bean 
    public InnerBean innerBean() { 
    InnerBean innerBean = new InnerBean(); 
    innerBean.setSimpleProp1("test123"); 
    return innerBean; 
    } 
} 

Main.java:

public class Main { 
    public static void main(String[] args) { 
    ApplicationContext ctx = new AnnotationConfigApplicationContext("com.acme"); 
    OuterBean outerBean = ctx.getBean("outerBean", OuterBean.class); 
    System.out.println(outerBean.getSimpleBean().getProp1().getSimpleProp1()); 
    } 
} 

Główna klasa używa AnnotationConfigApplicationContext skanować zarówno @Configuration i @Component adnotacji i tworzenie fasoli odpowiednio.

+0

W moim kodzie zmieniono adnotację z @ Konfiguracja na @ Komponent w obu klasach: ProstyBean i WewnętrznyBean. Nadal dostaję ten sam błąd.Nadal narzeka "Nie znaleziono domyślnego konstruktora". –

+0

Testowałem przykładowy kod, który dostarczyłem w wersji 3.0.6 i wypisuje "test123". Którą wersję sprężyny używasz? Możesz chcieć pokazać więcej konfiguracji, ponieważ nazwa klasy 'com.domain.SimpleBean $$ EnhancerByCGLIB $$ 4bc418be. () 'sugeruje, że są zaangażowane dalsze proxy. – beny23

+0

Przetestowałem to używając tylko słoików z wersji 3.0.6. Kiedy zaznaczyłem klasy za pomocą @ komponentu zamiast @ konfiguracji; miał podobny błąd. Tylko część CGLIB nie była zaangażowana. –

Powiązane problemy