我的主要类(class)如下。
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
SimpleCommandLinePropertySource cmdLineSrc = new SimpleCommandLinePropertySource(args);
ctx.getEnvironment().getPropertySources().addFirst(cmdLineSrc);
ctx.register(MyConfig.class);
ctx.refresh();
ctx.start();
MyClass myclass = ctx.getBean(MyClass.class);
// do something...
}
现在在我的 MyApp.config 中,我有以下内容..
@Autowired
Environment env;
但是,当我尝试获取值时,我得到了 NPE。
env.getProperty("something");
我在这里缺少什么?我确实有如下 @PropertySource (效果很好),但这会导致这里出现任何问题吗?
@Configuration
@PropertySource({ "classpath:my.properties" })
public class MyConfig {
@Autowired
private Environment env;
最佳答案
@PropertySource 声明覆盖了我的 @Configuration 类中的环境变量。我删除了它,并且能够检索我在命令行中输入的值。
关于java - 如何从命令行读取值并在引导注释配置类中使用它们来定义spring bean?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25374178/