主要:
@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();
}
}
当我尝试 Autowiring 它时,我得到了这个异常:
***************************
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 组件中 Autowiring Test
。例如,
package my.pkg.example;
@Component
public class TestExample {
@Autowired
private Test tst;
}
关于java - 如何使用注释Bean和ComponentScan正确创建Spring bean?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46962940/