2016-06-18 7 views
0

--Appconfig.javaKann Arbeit ohne @componentScan (Frühling JavaConfig @annotaion)

@Configuration 
public class AppConfig {  

    @Bean(name="helloBean") 
    public HelloWorld helloWorld() { 
    return new HelloWorldImpl(); 
    } 
} 

--interface.java

public interface HelloWorld { 
    void printHelloWorld(String msg); 
} 

--ipml.java

public class HelloWorldImpl implements HelloWorld { 
public void printHelloWorld(String msg) { 
    System.out.println("Hello! : " + msg); 
    -- 
} 
@Configuration

--App.java

public class App { 

public static void main(String[] args) { 

    AnnotationConfigApplicationContext context = new 
    new AnnotationConfigApplicationContext(AppConfig.class); 

HelloWorld obj = (HelloWorld) context.getBean(HelloWorldImpl.class); 

obj.printHelloWorld("Spring3 Java Config"); 
    } 
} 

Mein Programm kann funktionieren, aber meine Frage ist, warum ich @componentScan in Appconfig.java nicht hinzufügen muss.

Es scheint @Configuration und @Bean kann von Spring ohne @componentScan gefunden werden.

Ich dachte, wenn Sie @annotation verwenden möchten, können Sie @componentScan verwenden müssen oder

context:component-scan(xml), bin ich recht?

Antwort

1

@ComponentScan ermöglicht Feder automatisches Scannen aller Ihrer Komponenten mit @Component annotiert. Spring verwendet das Basispaketattribut, das anzeigt, wo Komponenten zu finden sind.

@Configuration ist ein Meta-Kommentar mit @Component, der für das Scannen von Klassenpfaden geeignet ist.

@Configuration (AppConfig Klasse) registriert ist, wenn Sie

verwenden
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); 

@Bean nicht @ComponentScan benötigt, da alle diese Bohnen explizit, wenn der Frühling Begegnungen diese Anmerkung erstellt werden.

+0

Ich habe es, vielen Dank. –

Verwandte Themen