您好我目前正在获取.properties
个文件的值。我遇到了一个问题。我正在使用Spring Boot。请参阅下面的示例来源;
Browser.java
@Controller
public class Browser {
@Autowired
private BrowserConfiguration conf;
public Browser(){
System.out.println("I am initializing...");
System.out.println("Reading configuration files..."+conf);
System.out.println("Starting selected browser...");
System.out.println("Waiting for command execution...");
}
}
BrowserConfiguration.java
@Configuration
@PropertySource("file:./properties/test-config.properties")
public class BrowserConfiguration {
@Value( "${browser.target}" )
private String browser;
public String getBrowser() {
return browser;
}
public void setBrowser(String browser) {
this.browser = browser;
}
@Override
public String toString(){
return "Target Browser: "+getBrowser();
}
}
Demo1Application.java
@SpringBootApplication
public class DemoApplication implements CommandLineRunner {
@Autowired
private Browser browser;
public static void main(String[] args) {
SpringApplication app = new SpringApplication(DemoApplication.class);
app.setBannerMode(Mode.OFF);
app.run(args);
}
@Override
public void run(String... arg0) throws Exception {
// TODO Auto-generated method stub
browser.runTest("test1");
}
}
test-config.properties
browser.target=ie
控制台日志
2017-04-29 23:51:10.537 INFO 6912 --- [ main] com.example.Demo1Application : Starting Demo1Application on Mikram-PC with PID 6912 (C:\Users\Mikram\sts-workspace\demo-1\target\classes started by Mikram in C:\Users\Mikram\sts-workspace\demo-1)
2017-04-29 23:51:10.540 INFO 6912 --- [ main] com.example.Demo1Application : No active profile set, falling back to default profiles: default
2017-04-29 23:51:10.576 INFO 6912 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@67b467e9: startup date [Sat Apr 29 23:51:10 SGT 2017]; root of context hierarchy
I am initializing...
Reading configuration files...null
Starting selected browser...
Waiting for command execution...
2017-04-29 23:51:11.051 INFO 6912 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
I am search now!
2017-04-29 23:51:11.062 INFO 6912 --- [ main] com.example.Demo1Application : Started Demo1Application in 0.722 seconds (JVM running for 1.02)
2017-04-29 23:51:11.063 INFO 6912 --- [ Thread-2] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@67b467e9: startup date [Sat Apr 29 23:51:10 SGT 2017]; root of context hierarchy
2017-04-29 23:51:11.064 INFO 6912 --- [ Thread-2] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
问题:
我似乎无法连接Browser类中的BrowserConfiguration。我错过了什么?请指出我正确的方向。我现在迷失了。
答案 0 :(得分:2)
您正在使用字段注入,但访问构造函数中的变量。因为在创建对象时调用构造函数,所以Spring还没有机会设置变量。在这种情况下,您必须使用基于构造函数的注入:
@Autowired
public Browser(BrowserConfiguration conf) {
this.conf = conf;
//Use the variable here
}