How to make final variable when #Value annotation is used - spring

I have read similar post in the forum but actually could not find an answer. I am reading a property from an application.yaml file but I want to make that variable final. But compiler does not allow me to do it and says the variable might not be initialized. What I want to do is to use final as below. So this variable is defined in a controller class.
#Value("${host.url}")
private final String url;
So how can I do it final ?

The only way to achieve it is using constructor injection.
#Component
public class MyBean {
private final String url;
public MyBean(#Value("${host.url}") String url) {
this.url = url;
}
}

Related

Spring #Value not working in Spring Boot 2.5.5, getting null values

I am trying to inject some property values into variables by means of Spring #Value annotation but I get null values. I tried different configurations and triks but it doesn't work. Think is that before today everythink was working properly. I do not know what I changed in order to get things broken.
Here is my java class:
#Component
#ConditionalOnProperty(prefix = "studioghibli", name = "get")
public class StudioGhibliRestService {
#Value("${studioghibli.basepath}")
private static String BASE_PATH;
#Value("${studioghibli.path}")
private static String PATH;
#Value("${studioghibli.protocol:http}")
private static String PROTOCOL;
#Value("${studioghibli.host}")
private static String HOST;
private static String BASE_URI = PROTOCOL.concat("://").concat(HOST).concat(BASE_PATH).concat(PATH);
#Autowired
StudioGhibliRestConnector connector;
public List<StudioGhibliFilmDTO> findAllFilms() throws SipadContenziosoInternalException {
var response = connector.doGet(BASE_URI, null, null);
if (!response.getStatusCode().is2xxSuccessful() || !response.hasBody()) {
throw new SipadContenziosoInternalException(Errore.INTERNAL_REST_ERROR, "FindAll(), microservizio ".concat(BASE_URI), null);
}
return (List<StudioGhibliFilmDTO>) response.getBody();
}
}
As you can see, the class is annotated with #Component, that because I will need to use it as #Service layer in order to make a rest call in my business logic.
The class is also annotaded with conditional on property...
Here is a screenshot of the debug window at startup:
Since the PROTOCOL value is null, i get a null pointer exception immediately at start up.
Here is part of the application-dev.properties file:
studioghibli.get
studioghibli.protocol=https
studioghibli.host=ghibliapi.herokuapp.com
studioghibli.basepath=/
studioghibli.path=/films
First of all, #Value annotation does not work with static fields.
Secondly, fields with #Value annotation is processed when the instance of the class (a bean) is created by Spring, but static fields exist for a class (for any instance), so when the compiler is trying to define your static BASE_URI field other fields are not defined yet, so you get the NPE on startup.
So you might need a refactoring, try to inject values with the constructor like this:
#Component
#ConditionalOnProperty(prefix = "studioghibli", name = "get")
public class StudioGhibliRestService {
private final StudioGhibliRestConnector connector;
private final String baseUri;
public StudioGhibliRestService(StudioGhibliRestConnector connector,
#Value("${studioghibli.basepath}") String basePath,
#Value("${studioghibli.path}") String path,
#Value("${studioghibli.protocol:http}") String protocol,
#Value("${studioghibli.host}") String host) {
this.connector = connector;
this.baseUri = protocol.concat("://").concat(host).concat(basePath).concat(path);
}
// other code
}
Thanks, It works for me, I have to add some codes to my project. Then I check the spring core document in "#Value" section. Besides
When configuring a PropertySourcesPlaceholderConfigurer using
JavaConfig, the #Bean method must be static.
#Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer(){
return new PropertySourcesPlaceholderConfigurer();
}

#Value not set in one specific class

I'm fairly sure I'm being some kind of idiot, but for the life of me I can't see it.
I have a large Spring Boot 2.1 application that extensively uses injection of properties through the #Value annotation. This works great, has done for years. But there's one specific, brand-new object where I can't get the values set. They are always null.
I know the problem isn't with the values themselves, because some of the same values inject just fine into other objects. But I just can't see what's wrong with THIS object, and would be grateful for your eyeballs.
The values in this object (which is in the same directory and builds just fine) are always null:
#Service
public class SSOUtil {
private String domain = "https://login.microsoftonline.com/";
private String tenantId = "[deleted guid]";
public static String localEnvironment = "local";
public static String devEnvironment = "dev";
public static String testEnvironment = "test";
public static String prodEnvironment = "prod";
#Value("${actions.PROD.touchnet_azure_ad_client_secret}")
private String clientSecretTouchnetProd;
#Value("${actions.TEST.touchnet_azure_ad_client_secret}")
private String clientSecretTouchnetTest;
#Value("${actions.DEV.touchnet_azure_ad_client_secret}")
private String clientSecretTouchnetDev;
#Value("${actions.touchnet_azure_ad_client_id_dev}")
private String clientIdDev;
#Value("${actions.touchnet_azure_ad_client_id_test}")
private String clientIdTest;
#Value("${actions.touchnet_azure_ad_client_id_prod}")
private String clientIdProd;
#Value("${touchnet.redirectURLDev}")
private String redirectURLDev;
#Value("${touchnet.redirectURLTest}")
private String redirectURLTest;
#Value("${touchnet.redirectURLProd}")
private String redirectURLProd;
private String clientId;
private String clientSecret;
private String redirectURI;
public SSOUtil() {
this.redirectURI = redirectURLTest;
this.clientSecret = clientSecretTouchnetTest;
}
public String getADLoginURL() {
String returnURL = "";
System.out.println(clientIdTest); // always prints null
}
}
The values in this object work just fine, though, and note that one of them is the same #Value as in the other class:
#Service
public class LibraryHelpServiceBean implements LibraryHelpService {
private CourseServiceBean courseServiceBean;
private final RestTemplate restTemplate;
#Value("${actions.libraryhelp_lti_api_key}")
private String apikey;
#Value("${actions.touchnet_azure_ad_client_id_test}")
String clientIdTest;
public LibraryHelpServiceBean(CourseServiceBean courseServiceBean, RestTemplateBuilder restTemplateBuilder) {
this.courseServiceBean = courseServiceBean;
this.restTemplate = restTemplateBuilder.build();
}
public void doesValueWork() {
this.apikey = this.apikey;
System.out.println(this.clientIdTest); // always prints correct value, a guid
}
}
Both objects are initialized in a similar way: either directly or indirectly through the #Autowired annotation in other objects that I use (and which work fine, and have worked fine for ages). Here's the creation of SSOUtil (my problem class):
#RestController
#RequestMapping(value = "/web")
public class SSOLandingController {
#Autowired
private SSOUtil ssoUtil;
[rest of class omitted]
}
And here's the creation of LibraryHelpServiceBean, which is working fine and has all #Values populate correctly:
#Service
public class LibraryHelpStreamServiceBean implements LibraryHelpStreamService {
private LibraryHelpServiceBean libraryHelpServiceBean;
public LibraryHelpStreamServiceBean(LibraryHelpServiceBean libraryHelpServiceBean){
this.libraryHelpServiceBean = libraryHelpServiceBean;
}
}
I have already tried changing the class annotation for SSOUtil from #Service to #Component (and #Configuration, just for the heck of it).
What could be causing the #Values in SSOUtil to come back null even though some of those same #Values populate just fine in other classes?
I'm convinced that I'm missing something obvious. I'm hoping it's something small like a typo. I'm nervous that it's something big, like I've completely misunderstood how Spring IOC works for the past several years.
Thanks for your help.
I tested your case on my computer, but I'm not able to reproduce your problem. When things like this is happening, try something very simple like this
package no.mycompany.springbootapp;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
#Component
public class SSOUtil2 {
#Value("${actions.touchnet_azure_ad_client_id_test}")
private String clientIdTest;
}
Inject this component into your controller, set a breakpoint inside your controller method and inspect the injected instance.
My experience is that some unexplainable cases I've been involved in here on SO, were solved by cleaning the build or wiping the .m2-folder.

Assign a value to a parameter in application properties before use

I have a property in my application.properties file in a SpringBoot project -
app.module.service.url=http://localhost:8090/{DOCID}
I have injected it into my Java file as below -
#Value("${app.module.service.url}")
private String url;
Now I need to replace DOCID with some value in my function(i.e-dynamic). How do I get to do this or am I completely missing it?
I am aware that we can do this in case of message properties in Spring. But here I have nothing to do with Locales.
Edit:
There is some value which I need to put in place of {DOCID} when using it within my Java implementation.
...
public class Sample{
#Value("${app.module.service.url}")
private String url;
public void sampleFunc(){
String str = "random Value" //some dynamic value goes in here
...
Now I need to replace {DOCID} with str in url
Two way binding is not possible in Spring Properties.It can only read run time and environmental variables.
Please refer following link for more information.
https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-Configuration-Binding
You can use spring UriTemplate for this purpose.
In your implementation class:
...
public class Sample{
#Value("${app.module.service.url}")
private String url;
public void sampleFunc(){
String dockId = someValue; // customize according to your need
UriTemplate uriTemplate = new UriTemplate(url);
URI uri = uriTemplate.expand(docId);
new RestTemplate().postForEntity(uri, requestObhect, Responseclass.class);
}
...
For more information, you can refer :
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/util/UriTemplate.html
Try like this ...
app.module.service.url=http://localhost:8090/{{docId}}
And set run configuration as below
-DdocId = 133323 // any number which you want

How to bind a string array of properties in Spring?

I have the following in my application.properties file
some.server.url[0]=http://url
some.server.url[1]=http://otherUrl
How do I refer to the array of properties using the #Value anotation inside a #Bean method?
I am using Java 6 with Tomcat 7 and Spring boot 1.4
I was also having the same problem as you mentioned and it seems using index form on application.properties was not working for me either.
To solve the problem I did something like below
some.server.url = url1, url2
Then to get the those properties I simply use #Value
#Value("${some.server.url}")
private String[] urls ;
Spring automatically splits the String with comma and return you an Array. AFAIK this was introduced in Spring 4+
If you don't want comma (,) as seperator you have to use SpEL like below.
#Value("#{'${some.server.url}'.split(',')}")
private List<String> urls;
where split() accepts the seperator
You can use a collection.
#Value("${some.server.url}")
private List<String> urls;
You can also use a configuration class and inject the bean into your other class:
#Component
#ConfigurationProperties("some.server")
public class SomeConfiguration {
private List<String> url;
public List<String> getUrl() {
return url;
}
public void setUrl(List<String> url) {
this.url = url;
}
}
Follow these steps
1)
#Value("${some.server.url}")
private List urls;
2)
#ConfigurationProperties("some.server")
public class SomeConfiguration {
3)
You should have getter and setter for instance variable 'urls'

Spring: How to inject a value to static field?

With this class
#Component
public class Sample {
#Value("${my.name}")
public static String name;
}
If I try Sample.name, it is always 'null'. So I tried this.
public class Sample {
public static String name;
#PostConstruct
public void init(){
name = privateName;
}
#Value("${my.name}")
private String privateName;
public String getPrivateName() {
return privateName;
}
public void setPrivateName(String privateName) {
this.privateName = privateName;
}
}
This code works. Sample.name is set properly. Is this good way or not? If not, is there something more good way? And how to do it?
First of all, public static non-final fields are evil. Spring does not allow injecting to such fields for a reason.
Your workaround is valid, you don't even need getter/setter, private field is enough. On the other hand try this:
#Value("${my.name}")
public void setPrivateName(String privateName) {
Sample.name = privateName;
}
(works with #Autowired/#Resource). But to give you some constructive advice: Create a second class with private field and getter instead of public static field.
Soruce of this info is this: https://www.baeldung.com/spring-inject-static-field
Spring uses dependency injection to populate the specific value when it finds the #Value annotation. However, instead of handing the value to the instance variable, it's handed to the implicit setter instead. This setter then handles the population of our NAME_STATIC value.
#RestController
//or if you want to declare some specific use of the properties file then use
//#Configuration
//#PropertySource({"classpath:application-${youeEnvironment}.properties"})
public class PropertyController {
#Value("${name}")//not necessary
private String name;//not necessary
private static String NAME_STATIC;
#Value("${name}")
public void setNameStatic(String name){
PropertyController.NAME_STATIC = name;
}
}
This is my sample code for load static variable
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
#Component
public class OnelinkConfig {
public static int MODULE_CODE;
public static int DEFAULT_PAGE;
public static int DEFAULT_SIZE;
#Autowired
public void loadOnelinkConfig(#Value("${onelink.config.exception.module.code}") int code,
#Value("${onelink.config.default.page}") int page, #Value("${onelink.config.default.size}") int size) {
MODULE_CODE = code;
DEFAULT_PAGE = page;
DEFAULT_SIZE = size;
}
}
For those who want to use ApplicationContext in the main class of a Spring Boot application, you can just use the return value of SpringApplication.run.
Although workarounds may need to be implemented, one should try to avoid them in most scenarios if possible. Spring is great at handling dependency injection and treats most objects as Singletons. This means that Spring can handle the creation of objects for you, and the injection of these objects at runtime. When combining this with the fact that your Spring managed bean is likely a Singleton, the use of static methods and variables is largely unnecessary. You can simply autowire in an instance of the object you are looking for at the constructor level or variable level and reference the non-static version of the method or variable. This is ideal and behaves similarly to a static reference. Non static variables are basically static because you are only ever using one instance of the object in every part of the code and because of dependency injection you are never handling the instantiation of the object, just like with a static reference! Great! Now I'm sure there are instances where you need the work around (i.e. you aren't using dependency injection or class is not a singleton), but try to not use workarounds if possible. Also this is just my 2 cents. Someone may be able to offer 3. (:
public class InjectableClass{
#Value("${my.value}")
private String myString;
public String nonStaticMethod(){
return myString;
}
}
public class LogicClass{
private InjectableClass injectableClass;
#Autowire
public LogicClass(InjectableClass injectableClass){
this.injectableClass = injectableClass;
}
public void logicClassMethod(){
System.out.println("Hey! Here is the value I set on myString: " +
injectableClass.nonStaticMethod() + ". That was
basically like using a static method!");
}
}

Resources