When ever we work in any application maintaing the environment specific files are very much required. In spring this can be achieved by using the profiles.
Look at the Following example. I am trying to fetch the url property and print it using the controller. To achieve this create a property files named, in the following path /src/main/resources.
application-dev.properties
url=http://mydevhost:8080/home
application-stage.properties
url=http://myStagehost:8080/home
In the application.properties define the following .
url=http://myhost:8080/home
spring.profiles.active=stage
Create a service class where you read this value as below.
package com.searchendeca.application.services;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
@Service
public class DemoService {
@Value("${url}")
private String Url;
public String getUrl() {
return Url;
}
public void setUrl(String url) {
Url = url;
}
}
Below is my Main class.
package com.searchendeca.application.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.searchendeca.application.services.DemoService;
@SpringBootApplication
public class DemoApplication {
@Bean
public DemoService getDemoService() {
return new DemoService();
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Controller
class Example {
@RequestMapping("/")
@ResponseBody
public String hello() {
return getDemoService().getUrl();
}
}
}
Now acces the Url: http://localhost:8080/
Below is the output.
http://myStagehost:8080/home
In some cases we can differentiate using the @profile anotation, this will work only the profile is passed as part of the VM argument or the application.properties
Happy Learning!!!
No comments:
Write comments