[英]How to inject pojo class in spring?
我有一个 pojo class 我需要注入组件。 如何在 spring 中注入 pojo object? 例如RestClass 在 Module 下(就像一个微服务)。 Pojo 值应仅在此处注入。 服务 class 和 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;
.
.
}
在您的情况下使用@Bean
注释。 例如:
使用@Configuration
注释创建一些配置文件。 无论您在何处创建Config
配置 class 或如何命名它都无关紧要。 您甚至可以在整个项目中拥有多个@Configuration
类。
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();
}
}
现在,您可以在任何使用它的地方自动装配它,就像您的示例一样。
您可以使用@Configuration 和@Bean。 像这样的东西
AppConfig.java
@Configuration
public class AppConfig {
@Bean
public PojoClass getBean(){ return new PojoClass();}
}
您可以使用@Bean
@Configuration
public class Config {
@Bean
public MyConfig MyConfig() {
return new MyConfig();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.