我需要在主类中使用@springbootapplication注释的环境

时间:2019-05-29 11:06:03

标签: spring-boot

我尝试在spring bootapplication的main方法中使用环境变量的自动装配,并尝试从application.properties获取值并将其分配给main方法类中的astring变量。当我打印并检查环境对象时,它会打印null并最终出现nullpointer异常

public class App 
{
    @Autowired
    private Environment env;

    public String getData(){
        System.out.println(env);
        System.out.println(env.getProperty("app.name"));
        return env.getProperty("app.name");
    }
    private  String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public static void main( String[] args )
    {

        System.out.println("name is "+new App().getData());
        SpringApplication.run(App.class, args);

    }
}                                                                           
***in application.properties***                        

    app.name=aravind
    app.city=mumbai~

    Am getting null pointerexception if i call getProperty method, also env object is printing null

1 个答案:

答案 0 :(得分:1)

您正在Main类内部进行自动装配。我认为这对您不起作用。

有关更多详细信息,请参见此[Spring Autowire inside of SpringBootApplication class is behaving differently between nearly identical applications]

您可以做的是创建其他类,然后将其标记为@Component,然后检索环境数据。

示例

@Component
public class TestClass{
@Autowired
    private Environment env;

@Autowired
TestClass(Environment env){ //this is constructor
System.out.println("App Name: "+getData());
}
  public String getData(){
        System.out.println(env);
        System.out.println(env.getProperty("app.name"));
        return env.getProperty("app.name");
    }
}

还在主类的@ComponentScan("yourpackagename")之后添加@SpringBootApplication