简体   繁体   English

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

[英]how to read values from command line and use them in bootstrapped annotation config class to define spring bean?

i have my main class as below. 我的主要课程如下。

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...
}

now in my MyApp.config, i have following.. 现在在我的MyApp.config中,我有以下内容。

@Autowired
Environment env;

however, when i try to get values out, i get NPE. 但是,当我尝试获取价值时,我得到了NPE。

env.getProperty("something");

what am i missing here? 我在这里想念什么? I do have @PropertySource as below (which works fine), but could that cause any issues here? 我确实有如下所示的@PropertySource(效果很好),但是这可能会引起任何问题吗?

@Configuration
@PropertySource({ "classpath:my.properties" })
public class MyConfig {

    @Autowired
    private Environment env;    

@PropertySource declaration was overriding environment variables in my @Configuration class. @PropertySource声明覆盖了我的@Configuration类中的环境变量。 i removed it and i was able to retrieve values i entered in command line. 我删除了它,并能够检索在命令行中输入的值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 spring 批处理使用 spring 启动:从配置或命令行读取 arguments 并在作业中使用它们 - spring batch using spring boot: Read arguments from config or command line and use them in job spring 从命令行批量读取作业参数并在作业配置中使用 - spring batch read jobParameters from command line and use it in job config 如何在Spring注释配置中为bean指定父级? - How to specify parent for bean in Spring annotation config? 在spring boot配置类中,为什么要使用Bean注释并将方法设置为“public”? - In spring boot config class, why should I use Bean annotation and set the method 'public'? 如何将xml配置bean转换为java注释bean(spring boot) - How to convert an xml config bean to java annotation bean ( spring boot ) 如何将依赖项 class 中的 bean 定义为 Spring 中的 @Primary? - How to define a bean from a dependency class as @Primary in Spring? Spring从属性文件中读取@Bean类的值 - Spring read values for @Bean class from properties file 如何从注释处理器中的嵌套注释中读取Class []值 - How to read a Class[] values from a nested annotation in an annotation processor Spring:使用@Value注释时,Bean无法从外部属性文件中读取值 - Spring: Bean fails to read off values from external Properties file when using @Value annotation 如何将Spring bean Oauth集成从XML转换为基于Java注释的Config - How to convert spring bean Oauth integration From XML to Java annotation based Config
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM