[英]Injecting a dependency into a library class not managed by spring
I am pretty new to spring or dependency injection. 我对spring或依赖注入很陌生。 I have an abstract class A in a jar file built already, which is not managed by Spring (This is based on the fact that it does not have any of its dependencies auto-wired, no spring annotations used in the library.).
我已经在一个jar文件中建立了一个抽象类A,该文件不是由Spring管理的(这是基于它没有自动关联其依赖项,在库中没有使用spring注释的事实。)
I have project which needs to use this class and want to inject my implementations of class A's dependency (say, of Type B). 我有一个需要使用此类的项目,并且想注入我对类A的依赖项(例如,类型B)的实现。 This project uses springboot.
该项目使用springboot。
How can I inject dependency of type B into A? 如何将B类型的依赖项注入A? I tried following : 1. Created a configuration (@Configuration) class and added a method getB() annotated as @Bean which will return object of type B using my implementation of B.
我尝试了以下操作:1.创建一个配置(@Configuration)类,并添加一个标注为@Bean的方法getB(),它将使用我的B实现返回类型B的对象。
@Bean
public B getB () {
return new MyB();
}
If you want to inject B
into A
you cannot. 如果要将
B
注入A
,则不能。 Since A
is not managed by Spring, the IOC container will never inject anything in a class that he does not know. 由于
A
不是由Spring管理的,因此IOC容器将永远不会在他不知道的类中注入任何东西。
The key to your problem is the way you want to get and use the instance of A
. 问题的关键是您要获取和使用
A
实例的方式。
If you want to use A
in your code managed by spring then you have to create yourself a factory for A
: 如果要在spring管理的代码中使用
A
,则必须为A
创建一个工厂:
@Bean
public A a() {
B b = new MyB();
A a = new A(b); // new A is not possible since A is abstract but you got the idea
return a;
}
// ...
class MyService {
@Autowired
A a;
void something() {
(a.b instanceof MyB) // true
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.