@Autowired
我的情况很奇怪
App的主要课程:
@Configuration
@EnableAutoConfiguration
@SpringBootApplication
@ComponentScan({"khartn", "khartn.torrentsuploader.processor"})
public class NewMain implements CommandLineRunner {
public static void main(String[] args) {
SpringApplicationBuilder builder = new SpringApplicationBuilder(NewMain.class);
builder.headless(false);
ConfigurableApplicationContext context = builder.run(args);
}
@Override
public void run(String... args) throws Exception {
}
}
组件类:
@Component("MyDirectoryReader")
public class MyDirectoryReader {
public MyDirectoryReader ( ) {
System.out.println("qqqqqqqqqqqqqqq");
}
public void readDir() {
try {
String initialPathStr = NewJFrame.jTextField1.getText();
System.out.println("initialPathStr " + initialPathStr);
Path dir = FileSystems.getDefault().getPath(initialPathStr);
DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.{torrent}");
for (Path path : stream) {
System.out.println(path.getFileName());
}
stream.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
当应用程序启动时,我看到,MyDirectoryReader类已初始化:
2015-04-11 21:42:29.405 INFO 9375 --- [.NewMain.main()] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@13d6044f: startup date [Sat Apr 11 21:42:29 SAMT 2015]; root of context hierarchy
qqqqqqqqqqqqqqq
配置类:
@Configuration
@ComponentScan({"khartn", "khartn.torrentsuploader.processor"})
public class AppConfig {
@Bean(initMethod = "init")
public NewJFrame mainForm() {
System.out.println("init mainForm");
return new NewJFrame();
}
}
在NewJFrame类中有自动连接字段
public class NewJFrame extends javax.swing.JFrame {
@Autowired
@Qualifier(value = "MyDirectoryReader")
MyDirectoryReader myDirectoryReader;
但是当NewJFrame显示并按下按钮时,
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
if (myDirectoryReader == null) {
System.out.println("myDirectoryReader is null");
}
// myDirectoryReader.readDir();
}
然后myDirectoryReader为空。
为什么MyDirectoryReader被初始化为Component,但没有自动连接到该字段?
答案 0 :(得分:3)
根据init方法的代码,你进行调用new NewJFrame().setVisible(true);
,但是,当你自己创建一个对象时,Spring不知道它并且自动装配不起作用。您必须使用Spring bean对象本身。我认为,如果将该行更改为this.setVisible(true)
,它应该正常工作(因为在实例化bean时执行init方法)。