Home > Software design >  Loading Spring-boot properties to POJO
Loading Spring-boot properties to POJO

Time:02-01

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?

CodePudding user response:

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);

CodePudding user response:

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.

  •  Tags:  
  • Related