我对Spring不是很熟悉,遇到以下情况:
存储库类:
@Repository
public class MyRepository {
// ...
}
使用存储库类的类:
public class MyClass extends AbstractClass {
@Autowired
private MyRepository myRepository;
//...
}
我知道如果我注释我的 MyClass
与 @Component
并将其与 @Autowired
一起使用, 然后是 @Autowired
MyRepository
解决就好了。
问题是我需要创建 MyClass
的新实例与反射。所以MyRepository
永远不会解决,并且始终为 null。
有没有办法使用@Autowired
在这种情况下?
更好地解释我的情况:
我有一些 AbstractClass
的实现.
在我的应用程序的设置阶段,我创建了一个 HashMap
这些实现。基本上:
{"MyClass", MyClass.class}
//...
然后我有一个通用的 Controller
映射到 url /{class}?options=...
使用 {class}
@PathVariable
, HashMap
以上和反射我能够根据给定的 options
创建一个类的实例(这部分很重要)。你们认为有更好的方法吗?
提前致谢
最佳答案
Spring 本身提供了一些在对象中进行 Autowiring 的功能
您通过 new
或 newInstance()
或其他任何方式创建的。
要使用它,您需要一个 AutowireCapableBeanFactory
您可以通过使用 @Autowired
的 Spring 正常依赖注入(inject)获得。
@Autowired
private AutowireCapableBeanFactory autowireCapableBeanFactory;
然后你使用它的autowireBean(Object)
方法
将 @Autowired
属性注入(inject)到您的 bean 中。
Object myBean = map.get(className).newInstance();
autowireCapableBeanFactory.autowireBean(myBean);
设计说明:
如果您真的需要上述方法,请仔细考虑。
AutowireCapableBeanFactory
的 javadoc建议不要在大多数用例中使用此接口(interface):
This subinterface of BeanFactory is not meant to be used in normal application code: stick to
BeanFactory
orListableBeanFactory
for typical use cases.Integration code for other frameworks can leverage this interface to wire and populate existing bean instances that Spring does not control the lifecycle of. This is particularly useful for WebWork Actions and Tapestry Page objects, for example.
关于java - 类新实例上的 Spring @Autowired,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52355132/