I have a pojo class which i need to inject in component. how to inject pojo object in spring? For example RestClass is under Module(like one microservice). Pojo Value should be injected here only. service class and pojo is different module.
@Controller
public class RestClass {
@Autowired
private ServiceClass serviceClass;
// How to apply MyConfig pojo object into ServiceClass
//like MyConfig.Builder().limit(100).build();
@PostMapping("/business")
private void callDoBusiness(){
serviceClass.doBusiness();
}
}
//// ServiceClass and Pojo class is under one module. Pojo object should not construct here. should be passed from another module
@Service
public class ServiceClass {
@Autowired
private MyConfig myConfig;
public void doBusiness(){
System.out.println(myConfig.getLimit())
}
}
@Builder
@Getter
public class MyConfig {
private int limit;
.
.
}
CodePudding user response:
@Bean
annotation is used in your case. For example:
Create some configuration file with @Configuration
annotation. It doesn't matter where you create your Config
configuration class or how you name it. You can even have multiple @Configuration
classes across your project.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
class Config {
// configure your MyConfig class here as a bean
@Bean
public MyConfig myConfig() {
return MyConfig.Builder().limit(100).build();
}
}
Now you can autowire it wherever you use it as in you example.
CodePudding user response:
You can use @Configuration and @Bean. Something like this
AppConfig.java
@Configuration
public class AppConfig {
@Bean
public PojoClass getBean(){ return new PojoClass();}
}
CodePudding user response:
You can use @Bean
@Configuration
public class Config {
@Bean
public MyConfig MyConfig() {
return new MyConfig();
}
}