0

I am new to spring boot. I have question related to how I should develop a scenario in spring boot.

I have one class (say SingleObject) having some fields in it. I want to create another object from SingleObject (say JsonObject) having some Json structure derived from values of fields in SingleObject.

For this conversion I am using static method of a Class (say Converter); where method takes input of SingleObject and returns an object of JsonObject.

How should I implement this scenario in spring?

Should I use @Configuration annotation for Converter Class with @Bean annotation for method which returns JsonObject?

If I have to use @Configuration annotation, how should I collect that bean in my main method for further processing?

Bsquare ℬℬ
  • 4,423
  • 11
  • 24
  • 44
Yogesh Gavali
  • 61
  • 1
  • 8
  • While the method is static you would not the object and so no need to annotate. If it is not static, you can create bean just annotating with `@Component` or you can either use `@Configuration` and `@Bean` annotation and define beans in the class – greengreyblue Nov 12 '18 at 09:44
  • looks similar to this https://stackoverflow.com/questions/11903053/difference-between-component-and-configuration-in-spring-3 – greengreyblue Nov 12 '18 at 09:48
  • Thank you Amidala for your response. If I am not using static can you explain me how should I use spring boot configuration annotation? – Yogesh Gavali Nov 12 '18 at 09:51

1 Answers1

0

@Configuration should be fine. The JsonObject bean will be autowired if you specify SingleObject as a dependency (i.e. parameter).

@Configuration
public class MyConfig {
    @Bean
    public SingleObject single() { return new SingleObject(); }

    @Bean
    public JsonObject json(SingleObject single) {
        return Converter.convert(single);
    }
}

You probably shouldn't access these beans from your main method, as your main method will necessarily be static and it requires a bit of a hack to do so: Accessing spring beans in static method

Michael
  • 41,989
  • 11
  • 82
  • 128
  • If I am fetching say 10 objects from DB as `SingleObject` and by passing it as a List to convert method and getting List then using @Bean annotation would be appropriate? – Yogesh Gavali Nov 12 '18 at 10:07
  • @YogeshGavali Not really. A `List` shouldn't usually be a bean. You might want some higher level class e.g. `class SomeService { private List objects; public List getJson() {... } }`. The service is a bean, and is responsible for fetching and storing the data as well as converting it. – Michael Nov 12 '18 at 10:13
  • How would you wire the different objects of `SingleObject` ? – greengreyblue Nov 12 '18 at 10:56