Get Application Name Spring boot - spring

I'm building a module to save the data into the database. After finishing the module I will make it into a JAR which is common and anyone will call static method. There is a parameter its name application name i don’t want pass this value I want get this value dynamic after add jar to any spring boot application , then any one call this static method retrieve name application dynamic , so the spring boot contains the application properties have value spring.application.name I want get this value inside my module it’s doable ? it’s possible to get this value
I searched and found this implementation:
#Value("${spring.application.name}")
private String appName;
My class:
public class BackEnd {
#Value("${spring.application.name}")
static String applicationName;
private static void saveData(String messsage) {
DAO dao= new DAO()
dao.saveData(messsage,applicationName);
}
}
So currently the applicationName value is null. Is it the correct implementation?

The property name is correct and used by a handful of Spring Boot projects. You need to define this property yourself as Spring Boot default is an empty value as per docs:
# IDENTITY (ContextIdApplicationContextInitializer)
spring.application.name= # Application name.
You can use the usual application.yml file e.g.
spring:
application:
name: MyApp

well, the property name is correct but you need to define that property in application.properties or application.yml file as follows.
if you are using application.properties file define property as follows
spring.application.name= # your application name
if you are using application.yml file define property as follows
spring:
application:
name: # your application name

Related

Spring Boot Properties as Environment variables

I have come across some behaviour which seems inconsistent in how spring boot handles environment variables in application properties files vs configuration property classes. I am unsure whether this is a bug in spring or an error in my understanding of what "ought" to happen.
I have
#Data
#ConfigurationProperties("foo")
#Validated
public class ClientProperties {
#NotBlank
private String apiKey;
#NotBlank
private String uri;
}
In the application.properties file I have:
foo.baseUri=https://system.appspot.com
foo.uri=${foo.baseUri}/Valuation?apikey=${foo.apiKey}&bar={bar}
Setting Just FOO_APIKEY
If I run my app with:
export FOO_APIKEY=DEF
Then I get
APPLICATION FAILED TO START
***************************
Description:
Binding to target class ClientProperties(apiKey=null, uri=https://system.appspot.com/Valuation?apikey=DEF&bar={bar}) failed:
Property: foo.apiKey
Value: null
Reason: may not be empty
Note that in the URI the api key is set as expected as well as the base URI
Setting Just FOO_API_KEY
Next, if instead, I try to set just this property (remove the old env var):
export FOO_API_KEY=ABC
Then my app starts, but the values are not as expected. My logs show:
API Key: ABC.
URI Property: ${foo.baseUri}/Insurance?apikey=${foo.apiKey}&bar={bar}.
Note that now the base uri also disappeared as well as the API key being missing.
Setting Both Properties FOO_API_KEY and FOO_APIKEY
When I set both environment variables the app starts but the apiKey property of ClientProperties holds the value of the FOO_APIKEY export, where as the uri property of ClientProperties holds the value of the FOO_API_KEY export.
API KEY IS: ABC.
URI IS: https://system.appspot.com/Insurance?apikey=DEF&bar={bar}.
Notes
I actually don't need the value from ClientProperties.apiKey. It's only ever used in the app via the ClientProperties.uri which is already being resolved in application.properties. However, I specify the property so that I can have validation to ensure the value gets set. I could remove the value from my class and everything would be ok - expect then I lose my validation.
Spring boot version is: 1.5.10.RELEASE

Unable to read values from external property file in Spring Boot

I have a running Spring Boot project. I want to read some environment specific properties from an external properties file.
I mentioned config files names and locations while starting the server as follows:
java -jar AllergiesConditions.jar --spring.config.name=application,metadata --spring.config.location=classpath:/,/APPS/SpringBoot/
The property files loads successfully(because i tried to log one of the external key values inside datasource bean and It printed successfully) But when i try to access a value using #Value annotation - It returns null.
My test Class is as follows:
#Component
public class testclass {
private Logger logger = LogManager.getLogger(testcla.class);
#Value("${sso.server}")
public String sso;
public void test(){
logger.info("sso url is: "+sso); //This sso is logged as null
otherStuff();
}
}
This test() function is called when a particular API is hit after server is running.
The external config file - metadata.properties contains this variable:
sso.server=1234test
Edit: As suggested in this apparently duplicate question I also tried adding #PropertySource(name = "general-properties", value = { "classpath:path to your app.properties"}) in main Application configuration class and It loaded the files, but still I get null value itself.
Can someone please help in what's going wrong here?? Does the testclass need some specific annotation OR it needs to be a bean or something??
Thanks in Advance :)
Thanks to M.Deinum for great input and saving my time
Just posting his comment as answer
Factually ${sso.server} cannot be null. If ${sso.server} couldn't be resolved, my application will break at startup itself.
So the obvious problem was that I was creating a new instance of testclass in my controller using
testclass obj = new testclass(); obj.test();
Rather I should be using spring managed instance by autowiring testclass in my controller.

Spring Boot Custom Properties - How to include externalize properties when class is not in the application context

It is hard to understand but for my application a required format. I have some custom libraries which are included at runtime and so they are not in the spring application context. To get apis from spring boot application I catched required apis and overhand this to my external classes.
To show an example:
HashValueService hashValueService
= (HashValueService) appContext.getBean("hashValueServiceImpl");
ServiceList srvList = new ServiceList();
srvList.setHashValueService(hashValueService);
In this way I'm able to get access to my database, which is in my application context.
I have a lot of properties distributed in the whole application. So I want to use the default application.properties to centralized often used properties in my application, like the keystore.
For that I edited application.properties with this line:
application.keystore=server.jks
But of course the usage of the Spring's #Value does show me a null for that attribute, because this class is not in my application context:
#Value("${application.keystore}")
private String keystore;
Do you have an idea to overhand this properties to this customer libraries? Maybe the creation of a new property file whould help? Thank u a lot.
Majority of Spring magic is done by BeanPostProcessors. Take a good look at them - link.
#Value wiring (and much more) is performed by AutowiredAnnotationBeanPostProcessor, you can use it for your purpose:
AutowiredAnnotationBeanPostProcessor beanPostProcessor =
appContext.getBean(AutowiredAnnotationBeanPostProcessor.class);
ServiceList srvList = new ServiceList();
beanPostProcessor.processInjection(srvList);
After that, your ServiceList should have String keystore field initialized.

Spring Properties showing as Null

I have a Spring Boot application, generated by JHipster.
Am trying to add some new properties to the application-dev.yml file but my class is seeing the values null, even after spending some hours with Google.
Added the following to the top of application-dev.yml:
host: 1.2.3.4
port: 5555
In my class I have
#Component
public class ExampleUtils {
#Value("${host}")
private String host;
#Value("${port}")
private String port;
}
The class is in a new directory under the source root.
Thanks in advance.
in your application.properties set
spring.profiles.active=dev
or when you run the application parse the command line args follows
-Dspring.profiles.active=dev
It is a good practice to add the new properties you add to a #ConfigurationProperties class.
At least this way I never had problems adding properties.
Have a look at the docs : http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-typesafe-configuration-properties

Set/override Spring / Spring Boot properties at runtime

At the project with Spring Boot we use application.properties but need to configure some of these properties (like port number of logging level) based on an external configuration. We access the configuration via API so it is known only at runtime.
Is there a way to override or set some Spring properties at runtime (for example using a bean) and if yes how can this be achieved?
You could do this with Spring Cloud Config
Just for the purpose of illustration, here's a relatively quick way to see dynamic property overrides at runtime:
First, for your bean to be able to pick up changed properties, you need to annotate it with
#RefreshScope
Add the spring cloud dependency to your spring boot app, eg for gradle
compile group: 'org.springframework.cloud', name: 'spring-cloud-starter', version: '1.1.1.RELEASE'
( NB You also need the spring boot actuator dependency.)
With the app running, you can view your current config at eg
http://localhost:8080/env
eg if you have a property 'my.property' in application.properties, you'll see something like:
"applicationConfig: [classpath:/application.properties]": {
"my.property": "value1",
etc
To change the value, POST my.property=value2 to /env as application/x-www-form-urlencoded
eg
curl -X POST http://localhost:8080 -d my.property=value2
GET /env again and you'll see the new value appears under the "manager" section
To apply the changed properties, do an empty POST to /refresh. Now your bean will have the new value.
Could you use system properties to pass in the variable? If you configure the PropertyPlaceholderConfigurer you can set the precedence of system properties vs file properties.
For example, something like:
#Bean public PropertyPlaceholderConfigurer placeHolderConfigurer() {
PropertyPlaceholderConfigurer props = new PropertyPlaceholderConfigurer()
props.setSystemPropertiesMode( PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE )
props.setLocations(new
PathMatchingResourcePatternResolver().getResources("classpath:/**.properties"));
props
}
The above would load your .properties file, but we set the priority to be system variables first, so if you set a system variable that will override the same variable in the config.
Alternatively, looking at the docs, Spring recommends defining a search order in your Environment:
[PropertyPlaceholderConfigurer is still appropriate for use when]
existing configuration makes use of the "systemPropertiesMode" and/or "systemPropertiesModeName" properties. Users are encouraged to
move away from using these settings, and rather configure property
source search order through the container's Environment; however,
exact preservation of functionality may be maintained by continuing to
use PropertyPlaceholderConfigurer.
Hopefully one of the above should sort out what you need?

Resources