Home > OS >  How can I get objects from property file in another classes?
How can I get objects from property file in another classes?

Time:11-09

So, I've Java Spring class

@Service
@ConfigurationProperties(prefix = "spring.phone")
@Data
public class PhoneProps {
   private List<String> testNumber = new ArrayList<>();

   @Bean
    public void display() {
        System.out.println(testNumber);
    }
}

I will use "display" in another class, but when I call it I get an empty array. But Bean method works correctly in this (PhoneProps) class.

Example: When I call in PhoneProps class (When works @Bean):

[998976460010, 998939378668]

When I call "display" in another class:

[]

How can I use objects from PhoneProps in another file? I use YAML file.

CodePudding user response:

You have two stages. First stage, load data by create object and second stage, @Bean. If create @Bean, all stages must be in it.

CodePudding user response:

Try the following:

@Service
public class PhoneProps {

   @Value("${spring.phone}")
   private List<String> testNumber = new ArrayList<>();

   public void display() {
      System.out.println(testNumber);
   }
}

@Bean annotation creates a bean from the returned object of the annotated method, so I guess you don't want that. Additionally, use @Value to inject properties.

Now the only thing you need is to inject PhoneProps in another Spring-managed Bean and call its display() method.

  • Related