2017-10-26 7 views
0

Main:Wie ordnungsgemäß Bean Bean Spring mit Anmerkungen Bean und ComponentScan?

@SpringBootApplication 
@ComponentScan(basePackageClasses = Application.class) 
public class Application { 

    public static void main(String[] args) { 
     SpringApplication.run(Application.class, args); 
    } 
} 

Prüfklasse:

public class Test { 

    @Bean 
    public Test test(){ 
     return new Test(); 
    } 
} 

und wenn ich versuche, es zu autowire dann habe ich diese Ausnahme:

*************************** 
APPLICATION FAILED TO START 
*************************** 

Description: 

Field test in TestWithAutowire required a bean of type 'Test' that could not be found. 


Action: 

Consider defining a bean of type 'rcms.backend.exception.Test' in your configuration. 


Process finished with exit code 1 

Es ist ich etwas Hut bin falsch machen, aber ich kann es nicht herausfinden.

Antwort

1

Sie können eine neue Konfiguration erstellen, lassen Sie uns SpringConfiguration sagen,

package my.pkg.config; 

@Configuration 
public class SpringConfiguration { 
    @Bean 
    public Test test(){ 
     return new Test(); 
    } 
} 

In Ihrem Application Klasse, können Sie die @ComponentScan Annotation mit den Basispakete hinzufügen, wo Sie Frühling möchten für die Klassen scannen,

@SpringBootApplication 
@ComponentScan(basePackageClasses = {"my.pkg.config", "my.pkg.example"}) 
public class Application { 

    public static void main(String[] args) { 
     SpringApplication.run(Application.class, args); 
    } 
} 

Jetzt können Sie Test in jeder Spring-Komponente autowire. Zum Beispiel

package my.pkg.example; 

@Component 
public class TestExample { 

    @Autowired 
    private Test tst; 

}