[英]Spring : creating beans with @Bean
I have an issue with beans creations:我对豆类创作有疑问:
@Bean
Service carService() {
return new Service(new CarRepository(), "car");
}
My issue is that CarRepository class
has a dependency to EntityManager em
variable (with @PersistenceContext
)我的问题是CarRepository class
依赖于EntityManager em
变量(使用@PersistenceContext
)
So if I use new
operator, I'm missing this dependency (because I'm instanciating myself the bean).因此,如果我使用new
运算符,我将缺少这种依赖性(因为我正在实例化自己的 bean)。
Also I have many services (CarService, BikeService etc...) and many repositories too (CarRepository, BikeRepository etc...).我还有许多服务(CarService、BikeService 等)和许多存储库(CarRepository、BikeRepository 等)。 So using annotations directly in classes seems difficult.所以直接在类中使用注解似乎很难。
So any solutions?那么有什么解决办法吗?
I think you need to annotate every repository class with @Repository
annotation.我认为您需要使用 @Repository 注释对每个存储库@Repository
进行注释。 And every service class with @Service
.每个服务 class 都带有@Service
。
In Spring you should not use the new operator for Services.在 Spring 中,您不应使用新的服务运营商。 Use the annotation使用注解
@Service
public classSomeClass {
or或者
@Component
public classSomeClass {
and your class can be injected via depnendency Injection.并且您的 class 可以通过依赖注入进行注入。 If you want to create a new custom bean that can be used via dependencyInjection This is what the @Configuration annotation is for.如果您想创建一个可以通过 dependencyInjection 使用的新自定义 bean,这就是 @Configuration 注释的用途。
@Configuration
public class ConfigurationClass{
@Bean
public SomeClass createSomeClass(){
return new SomeClass();
}
}
Simple.简单的。 Pass your repository as dependency into your Bean factory function:将您的存储库作为依赖项传递到您的 Bean 工厂 function:
@Bean
Service carService(final CarRepository carRepository) {
return new Service(carRepository, "car");
}
The repository needs to exist as a bean itself.存储库需要作为 bean 本身存在。 You can create the repository bean in another bean method of a configuration class, or by annotating the class and having it created during component scanning.您可以在配置 class 的另一个 bean 方法中创建存储库 bean,或者通过注释 class 并在组件扫描期间创建它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.