繁体   English   中英

如何使用注解Bean和ComponentScan正确创建Bean Spring?

[英]How to proper create bean Spring using annotations Bean and ComponentScan?

主要:

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

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

测试类别:

public class Test {

  @Bean
  public Test test(){
      return new 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

我做错了什么事,但我找不到。

您可以创建一个新配置,比如说SpringConfiguration

package my.pkg.config;

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

在您的Application类中,您可以将@ComponentScan批注添加到您希望Spring扫描类的基本包中,

@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;

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM