假设我有界面栏:
public interface Bar {
void lengthyOperation ();
}
它的实现 Foo:
@Service
public class Foo implements Bar {
void lengthyOperation () {
// lengthy operation implementation
}
}
我还有一个名为 MyClass 的单例类:
public class MyClass implements Runnable {
@Autowired private final Bar bar;
private final Thread thread;
private static MyClass instance;
private MyClass () {
thread = new Thread (this);
thread.start();
}
public static MyClass getInstance () {
if (instance == null) instance = new MyClass();
return instance;
}
public void run() {
while (true) {
bar.lengthyOperation();
Thread.sleep(5000);
}
}
}
如何使用 @Autowired 注释(或任何其他可能的方式)将 Bar 注入(inject) MyClass 中?我尝试使用@Autowired private Final Bar 酒吧;但它始终为空;
如果无法实现,是否有办法防止调用 @Autowired 构造函数两次?如果你不明白我的意思,让我告诉你。这段代码:
@Controller
public class MyClass implements Runnable {
private final Bar bar;
@Autowired
public MyClass (Bar bar) {
this.bar = bar;
thread = new Thread (this);
thread.start();
}
public void run() {
System.out.println("New thread...");
while (true) {
bar.lengthyOperation();
Thread.sleep(5000);
}
}
}
将在控制台中打印两次“新线程...”。 也许(可能)有更优雅的方式来做到这一点,但我不知道......任何帮助将不胜感激!
谢谢!
编辑#1迪莫尼问我如何创建我的类的实例。基本上,MyClass 的实例必须在 WebApp 启动时创建,所以我使用了以下代码:
@Component
public class StartMyClass implements ApplicationListener<ApplicationEvent> {
public void onApplicationEvent(ApplicationEvent e) {
MyClass.getInstance();
}
}
最佳答案
如何创建 MyClass
实例?
@Autowired 不起作用,因为您的 MyClass 实例不是由 Spring 管理的。您需要在 Java/XML spring 配置中创建 MyClass
实例,或者使用 @Component
注释对其进行注释,并确保 MyClass 的包可以被 spring 扫描。
您的 @Controller
注释不正确,因为您的类显然不是 Controller ...
例如:
@Configuration
public class MiscConfiguration {
@Bean
public MyClass myClass() {
return new MyClass();//Will be created/managed by Spring, @Autowired will work
}
}
关于java - 我的单例类中的依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24290228/