Sunday, April 19, 2020

[Spring] Setting empty objects with spring Java code

Setting up empty objects with Java code

 Setting up empty objects with Java code
In addition to setting up xml, you can also create and set Java code for setting empty objects.


Config.java
@Configuration
public class Config {}
 First, create a class to set up an empty object and attach @Configuration. @Configuration indicates that the class is capable of spring setup.

@Configuration
public class Config {
 
    @Bean
    public A a() {
     return new A();
    }
    
    @Bean
    public B b() {
     return new B();
    }
}
 Define a method to return classes to be registered as empty objects and attach @Bean. @Bean means that each method generates one empty object. And method names act as identifiers to distinguish empty objects.

@Configuration
public class Config {
 
    @Bean
    public A a() {
     return new A();
    }
    
    @Bean
    public B b() {
     return new B(new A());
    }
}
 To inject object A into object B, create and pass object A as a factor in the constructor. Class B must have a constructor declared to receive object A as a factor.

Setting the Java code as above creates the same empty object as you did in xml setup.

No comments:

Post a Comment