Loading Spring-boot properties to POJO - java

I have properties like this:
credentials:
userid: <userid>
password: <password>
I have a POJO:
#Setter
public class Credentials {
private String userid;
private String password;
However, this POJO is in another jar, so I can't add annotations. So I thought I'd try something like this:
#Configuration
#Getter
#Setter
#ConfigurationProperties("credentials")
public class MyCredentials {
private Credentials credentials = new Credentials();
}
But I can't get my class to load the properties. How can I get it to work in this scenario?

Just make a separate configuration bean and access value from that try below code
#Configuration
#Getter
#Setter
#ConfigurationProperties("credentials")
public class MyCredentialSetting{
private String userid;
private String password;
}
Now wherever you want to use just use #Autowired like in controller or service
Here myCredentialSetting has value from propertoes file injected by spring boot automatically
#Autowired
private MyCredentialSetting myCredentialSetting;
String userIdValue=myCredentialSetting.getUserid(); //you will get user id value by this
String password=myCredentialSetting.getPassword();
//Setting value to original pojo for furthur use
private Credentials credentials = new Credentials();
credentials.setUserid(userIdValue);
credentials.setPassword(password);

You are mixing things.
#Setter (and #Getter) are most likely lombok project annotations.
These annotations at compile time will generate the getX() and setX() methods on a Pojo with a property "x".
If the Credentials POJO is in another jar, it should have a getter and setter (or it is not a POJO). So we don't care about lombok.
On another side you have a #Configuration class where Spring boot will create the different beans of your application.
The class should look something like this:
#Configuration
#ConfigurationProperties("credentials")
public class MyCredentials {
#Bean("credentials")
public Credentials credentials(
#Value("${credentials.userid}") String userid,
#Value("${credentials.password}") String password) {
Credentials credentials = new Credentials();
credentials.setUserid(userid);
credentials.setPassword(password):
return credentials;
}
}
With the #Value annotation Spring boot will inject the properties into the method that will create the bean.
EDIT I
As stated by #M.Deinum, the same can be obtained by:
#Configuration
public class MyCredentials {
#Bean("credentials")
#ConfigurationProperties("credentials")
public Credentials credentials() {
return new Credentials();
}
}
#ConfigurationProperties will find the properties prefixed with "credentials" and inject them into the credentials bean.
Thanks for the tip #M.Deinum!

Related

Spring Inject Values with #ConfigurationProperties and #Value

How to inject values from yaml and set default values if a property is not defined in the yaml props file? Is using both ConfigurationProperties and Value like below a good use? If not how else can we achieve it?
Properties file
app:
prop1: test
prop2: true
map:
key1: value1
key2: value2
Java class:
#Data
#Validated
#ConfigurationProperties("app")
public class properties {
private String prop1;
#Value("${app.prop2:default}")
private Boolean prop2;
#NestedConfigurationProperty
#NotNull
private Map<String,String> prop3;
}
Is using both ConfigurationProperties and Value like below a good use
No. #ConfigurationProperties indicates to spring that it should bind the java fields based on their name to some matching properties. However to achieve that spring requires that the class that has this annotation must be a spring bean (proxy class). So you have to use it together with either #Configuraiton or #Component or some other annotation that creates a spring bean for this class.
There is also some other functionality available where you can use another annotation #EnableConfigurationProperties(properties.class) on some other spring bean (not the current class that has the #ConfigurationProperties annotation)
Most common is that you use the #Configuration and then spring will be able to create a spring bean (proxy of this class) and then bind the values that you expect on the fields that you have.
Since you already have the #ConfigurationProperties("app"), then the property with the name prop2 will be bound with the application property app.prop2
#Data
#Validated
#Configuration <---------------
#ConfigurationProperties("app")
public class properties {
private String prop1;
private Boolean prop2;
#NestedConfigurationProperty
#NotNull
private Map<String,String> prop3;
}
If your problem is the default values in case the properties do not exist at all in application.properties then you can just initialize those java fields with some values.
#Data
#Validated
#Configuration <---------------
#ConfigurationProperties("app")
public class properties {
private String prop1 = "default";
private Boolean prop2 = false;
#NestedConfigurationProperty
#NotNull
private Map<String,String> prop3;
}

#Document Annotation for Collection Name in MongoDb for Java models Generated through Swagger in Spring boot Application

Steps I am following
I write Swagger File for API contract and Definition models for my Microservice
Now I am using Swagger codegen dependencies in my Spring boot application to generate Models from reading the Swagger from URL where it is hosted in target (output directory mentioned in pom.xml) directory of my application on "mvn install".
For each definition in the Swagger file One model class will be generated in my application's target directory.
Now I am using mongoDB as database for models to save as collection.
Need to Give #Document(value = "collection-name") - dynamically for model classes.
As model class are generated through Swagger codegen cant edit those,
So how to Maintain Dynamic Name for definitions which I want to save in DB
Is there any way through Swagger Contract to define this ?
A while ago I was struggling with this same problem, and some solutions include post-processing the generated files.
However, as a security concern, exposing the MongoDB model to the API might not be completely right. An interesting approach would be to simply use Mappers and apply the DTO concept to the auto-generated model classes.
For instance:
Suppose you have a users collection in MongoDB, and an API to retrieve the users.
components:
schemas:
User:
type: object
properties:
id:
type: string
name:
type: string
The Swagger auto-generated class would be something like this:
package api;
#ApiModel()
#Validated
public class User {
#JsonProperty("id")
private String id = null;
#JsonProperty("name")
private String name = null;
}
You will also have the 'standard' User model class:
package model;
#Document(collection = "users")
public class User {
#Id
private String id;
#NotNull
private String name;
#NotNull
private String password;
}
Notice for example, that the password field is not included in the API definition.
Then we'll have the typical User repository:
public interface UserRepository extends MongoRepository<User, String> { }
Now we have to implement the mapper, which is very straightforward using MapStruct:
#Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface UserMapper {
api.User map(model.User user);
}
You can widely customize which and how to map the information.
The only thing remaining is the controller:
#Controller
public class MyController implements MyApi {
#Inject
UserMapper mapper;
#Autowired
private UserRepository repository;
#GetMapping("/api/v1.0/users")
public ResponseEntity<List<api.User>> getAllUsers() {
List<api.User> users = new ArrayList<>();
repository.findAll().forEach(user -> users.add(mapper.map(user)));
return new ResponseEntity(users, HttpStatus.OK);
}

Read application variable (assoc array) form application.yml / java, spring

I am working on a spring project where I need to read multiple account credentials (login and password) from application yml file.
I have written the credentials as an associative array like this (I don't know any better way to do it):
app:
mail:
accounts:
- login: firstlogin
password: firstpassword
- login: secondlogin
password: secondpassword
Then I mapped these values to spring application with #Value annotation:
#Service
public class MyClass {
#Values("${app.mail.accounts}")
private List<Map<String, String>> accounts;
...
}
But spring keep throwing an Exception because it fails to read these values.
Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException:
Could not resolve placeholder 'intelaw.mail.accounts' in value "${app.mail.accounts}"
Without changing your application.yml, you can tune your datastructures and make this work.
Create a class Account
class Account {
private String login;
private String password;
//constructors, getters and setters here
}
and read it using a class annotated with #ConfigurationProperties
#Component
#ConfigurationProperties("app.mail")
class MyClass {
private List<Account> accounts = new ArrayList<>();
//getters and setters here
}
and in your service class, you can use it like :
#Autowired
private MyClass myClass;
void someMethod() {
myClass.getAccounts();
}

Spring Boot initialize new instance for nested configuration binding when there are no corresponding nested key/value pairs in application.properties

I have a configuration class like below. All of fields in the inner class OptionalServiceConfigs has a default value as annotated using #Value as shown in below.
Sometimes in my application.properties file, it does not have a single service prefixed property. In that case, we want to have loaded an OptionalServiceConfigs instance with its default field values.
#Configuration
#ConfigurationProperties(prefix = "myconf")
public class MyConfigs {
// ... rest of my configs
#Value("${service:?????}") // what to put here, or can I?
private OptionalServiceConfigs service; // this is null
// In this class all fields have a default value.
public static class OptionalServiceConfigs {
#Value("${mode:local}")
private String mode;
#Value("${timeout:30000}")
private long timeout;
// ... rest of getter and setters
}
// ... rest of getter and setters
}
But unfortunately, the service field is null when it is accessed using its getter method. Because spring boot does not initialize an instance of it when there is no property keys found with prefixed myconf.service.* in my application.properties file.
Question:
How can I make service field to initialize to a new instance along with its specified default field values when there are no corresponding prefixed keys in properties file?
I can't imagine a value to put in annotation #Value("${service:?????}") for service field.
Nothing works, tried, #Value("${service:}") or #Value("${service:new")
Based on #M. Deinum's advice, did some changes to configuration class. I am a newbie to Spring and it seems I have misunderstood how Spring works behind-the-scenes.
First I removed all #Value annotation from inner class (i.e. OptionalServiceConfigs), and as well as service field in MyConfigs class.
Then, initialized all inner class fields with their default values inline.
In the constructor of MyConfigs, I initialized a new instance of OptionalServiceConfigs for the field service.
By doing this, whenever there is no service related keys in my application.properties a new instance has already been created with default values.
When there is/are service related key/s, then Spring does override my default values to the specified values in application.properties only the field(s) I've specified.
I believe from Spring perspective that there is no way it can know in advance that a referencing field (i.e. service field) would be related to the configurations, when none of its keys exist in the configuration file. That must be the reason why Spring does not initialize it. Fair enough.
Complete solution:
#Configuration
#ConfigurationProperties(prefix = "myconf")
public class MyConfigs {
// ... rest of my configs
private OptionalServiceConfigs service;
public static class OptionalServiceConfigs {
private String mode = "local";
private long timeout = 30000L;
// ... rest of getter and setters
}
public MyConfigs() {
service = new OptionalServiceConfigs();
}
// ... rest of getter and setters
}
you can try such a structure which works for me quite fine:
#Data
#Validated
#ConfigurationProperties(prefix = "gateway.auth")
#Configuration
public class AuthProperties {
#NotNull
private URL apiUrl;
#Valid
#NotNull
private Authentication authentication;
#Data
public static class Authentication {
#NotNull
private Duration accessTokenTtl;
#NotNull
private String accessTokenUri;
#NotNull
private String clientId;
#NotNull
private String clientSecret;
#NotNull
private String username;
#NotNull
private String password;
#Min(0)
#NonNull
private Integer retries = 0;
}
}
Important is to have getters and setters in order to enable Spring to postprocess ConfigurationProperties, I am using Lombok (#Data) for this.
please see here for more details:
Baeldung ConfigurationProperties Tutorial

Store user info in spring environment

I get userId from request.getRemoteUser(), I want to store it somewhere and get from any layer of application. I don't want to pass the userId from controller to other layers or store it in context. Is there anything similar to this, so that simply autowired userId and use it anywhere.
I'm using Spring-boot and Spring-rest controller.
#Configuration
public class ConfigurationClass {
private #Value("#{ request.getRemoteUser() }") String userId;
#Bean("userId")
#Scope("request")
public String getUserId() {
return userId;
}

Categories

Resources