Monday 23 July 2018

Spring boot: inject application arguments using @Value annotation

Step 1: Rregister command line arguments to 'CommandLinePropertySource' 

Step 2:  Inject single application argument with @Value annotation.

Find the below working application.

MyBean.java
package com.sample.myApp.model;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class MyBean {

 @Value("${landscape}")
 private String workingEnvt;

 public String getWorkingEnvt() {
  return workingEnvt;
 }

 public void setWorkingEnvt(String workingEnvt) {
  this.workingEnvt = workingEnvt;
 }

}

Application.java
package com.sample.myApp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.SimpleCommandLinePropertySource;

import com.sample.myApp.model.MyBean;

@SpringBootApplication
public class Application {

 public static void main(String args[]) {

  SimpleCommandLinePropertySource propetySource = new SimpleCommandLinePropertySource(args);

  ConfigurableApplicationContext applicationContext = SpringApplication.run(Application.class, args);

  applicationContext.getEnvironment().getPropertySources().addFirst(propetySource);

  MyBean myBean = applicationContext.getBean(MyBean.class);
  String workingEnvt = myBean.getWorkingEnvt();
  System.out.println("Working Environment : " + workingEnvt);

  applicationContext.close();
 }

}

When you ran 'Application.java' application, you can see below message in the console.


Working Environment : development




Previous                                                 Next                                                 Home

No comments:

Post a Comment