【发布时间】:2022-01-23 16:31:21
【问题描述】:
我有一个 pojo 类,我需要在组件中注入它。如何在春天注入 pojo 对象? 例如 RestClass 在 Module 下(就像一个微服务)。 Pojo 值应仅在此处注入。服务类和 pojo 是不同的模块。
@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;
.
.
}
【问题讨论】:
-
作为最简单的方法,您是否考虑过在
Config-annotated 配置中创建一个返回MyConfig实例的Bean-annotated 方法? -
@Bean 的值将如何设置? ServiceClass 和 Pojo 类在一个模块中。控制器是其他模块吗?在哪里创建@Configuration。你能帮忙吗?
-
模块没有任何作用。再说一遍:赞成的答案是建议您这样做。请注意,您还可以将
@Value-annotated 参数注入该方法。到目前为止,我看不到真正的问题。