2017-10-26 17 views
0

メイン:注釈を使用してBeanを作成する方法BeanとComponentScan?

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

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

Testクラス:私は何かの帽子が

*************************** 
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 

あり:

public class Test { 

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

と私はそれをautowireしようとしているとき、私は、この例外が発生しました間違っているが、私はそれを見つけることができません。

答えて

1

あなたは新しい構成を作成することができます、のSpringConfigurationを言わせて、

あなた Applicationクラスで
package my.pkg.config; 

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

、あなたが

、あなたは春がクラスをスキャンしたい基本パッケージと @ComponentScan注釈を追加することができます
@SpringBootApplication 
@ComponentScan(basePackageClasses = {"my.pkg.config", "my.pkg.example"}) 
public class Application { 

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

これで任意のSpringコンポーネントにTestをオートワイヤできます。たとえば、

package my.pkg.example; 

@Component 
public class TestExample { 

    @Autowired 
    private Test tst; 

} 
関連する問題