java - 如何从命令行读取值并在引导注释配置类中使用它们来定义spring bean?

标签 java spring command-line configuration

我的主要类(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/

相关文章:

command-line - 使用 cmd.exe 中的关联性启动可执行文件 (Windows XP)

c - 读取多个文本文件(或执行两次?)时出现 free() 问题

javascript - 获取枚举并发送枚举值

java - volley.parsererror :org. json.JSONException : value br of type java. lang.string 无法转换为 JSONObject

java - Spring 事务管理的问题?

Spring Boot i18n 解析

ruby-on-rails - 使用一些参数运行 rails runner

java - 如何获取 jruby/warbler jar 文件的路径

java - 使用 jdbc 时尝试连接到远程 pg db 时出现奇怪的错误

java - Spring boot + angular 2 Heroku部署