我最近开始探索Spring Boot
。我看到有两种方法可以在Beans
中定义Spring Boot
。
@Bean
注释的类中定义@SprinBootApplication
@Bean
注释的类中定义@Configuration
我也对
stereo-type annotation
@Repository
@Service
@Controller
等感到困惑。有人可以解释一下这些注释如何进行依赖注入吗?
最佳答案
是的,有可能。
您可以在任何@Configuration或@SpringBootApplication类中使用@Bean,或者使用诸如@ Service,@ Component @Repository等的批注明确标记Bean类。
@服务或@Component
当您使用@Service或@Compoenent标记一个类,并且如果spring的注释扫描范围允许它到达包时,spring会将这些类的实例注册为spring beans
。
您可以使用@ComponentScan
提供要在扫描期间包含/排除的软件包
@Bean @Beans
在工厂方法上标记,该方法可以创建特定类的实例。
@Bean
public Account getAccount(){
return new DailyAccount();
}
现在在您的应用程序中,您可以简单地使用@Autowire Account,spring会在内部调用其工厂方法
getAccount
,该方法又返回DailyAccount
的实例。使用@Bean与@Service或@Compoenent有一个简单的区别。
第一个使您的豆彼此松散耦合。